Search code examples
ruby-on-railsactive-model-serializersrails-apiserialization

Apply method to all attributes using active_model_serializers


Using rails-api/active_model_serializers, could one apply a method to all attributes?

Basically, I wish to apply

object.zeroed_value(:symbol) 

to each attribute without having to write a separate method for each. See example:

class NutritionalSerializer < ActiveModel::Serializer
  attributes :calories,
             :sodium

  def calories
    object.zeroed_value(:calories)
  end

  def sodium
    object.zeroed_value(:sodium)
  end

  # many, many more attributes...

end


Solution

  • I think you can use metaprogramming to generate all methods you need with something like:

    class NutritionalSerializer < ActiveModel::Serializer
      attributes :calories,
                 :sodium
    
      %i{attr1 attr2 attr3}.each do |attr|
        define_method attr do
          object.zeroed_value(attr)
        end
      end
    end
    

    Also you can override the attributes method of serializer and then do something like:

    class NutritionalSerializer < ActiveModel::Serializer
      def attributes
        data = super
        %i{attr1 attr2 attr3}.each do |attr|
          data[attr] = object.zeroed_value(attr)
        end
        data
      end
    end