I have seen this code in discourse_signatures plugin
User.register_custom_field_type('see_signatures', :boolean)
User.register_custom_field_type('signature_url', :text)
User.register_custom_field_type('signature_raw', :text)
if SiteSetting.signatures_enabled then
add_to_serializer(:post, :user_signature, false) {
if SiteSetting.signatures_advanced_mode then
object.user.custom_fields['signature_raw']
else
object.user.custom_fields['signature_url']
end
}
# I guess this should be the default @ discourse. PR maybe?
add_to_serializer(:user, :custom_fields, false) {
if object.custom_fields == nil then
{}
else
object.custom_fields
end
}
end
In discourse national flags plugin
User.register_custom_field_type('nationalflag_iso', :text)
if SiteSetting.nationalflag_enabled then
byebug;
add_to_serializer(:post, :user_signature, false) {
object.user.custom_fields['nationalflag_iso']
}
byebug;
# I guess this should be the default @ discourse. PR maybe?
add_to_serializer(:user, :custom_fields, false) {
if object.custom_fields == nil then
{}
else
object.custom_fields
end
}
end
I am not able to understand what is add_to_serializer
is doing.
I checked in def add_to_serializer
def add_to_serializer(serializer, attr, define_include_method=true, &block)
klass = "#{serializer.to_s.classify}Serializer".constantize rescue "#{serializer.to_s}Serializer".constantize
klass.attributes(attr) unless attr.to_s.start_with?("include_")
klass.send(:define_method, attr, &block)
return unless define_include_method
# Don't include serialized methods if the plugin is disabled
plugin = self
klass.send(:define_method, "include_#{attr}?") { plugin.enabled? }
end
I understand that User.register_custom_field_type('signature_raw', :text)
will register a custom field type to User
object. But what is add_to_serializer
doing? I am not able to understand, can you explain me in plain english?