say I have this serializer
    class FooSerializer < ActiveModel::Serializer
      attributes :this, :that, :the_other
      def this
        SomeThing.expensive(this)
      end
      def that
        SomeThing.expensive(that)
      end
      def the_other
        SomeThing.expensive(the_other)
      end
    end
Where the operations for the individual serialized values is somewhat expensive...
And then I have another serializer that whats to make use of that, but not return all of the members:
    class BarSerializer < FooSerializr
      attributes :the_other
    end
This does not work... BarSerializer will still have this, that, and the_other...
How can I make use of inheritance but not automatically get the same attributes? I am looking for a solution other than module mixins.
ActiveModel::Serializer At a basic level, it means that if we have a Post model, then we can also have a PostSerializer serializer, and by default, Rails will use our serializer if we simply call render json: @post in a controller.
Serializers in Ruby on Rails convert a given object into a JSON format. Serializers control the particular attributes rendered when an object or model is converted into a JSON format.
Serialization is the process of converting a data object—a combination of code and data represented within a region of data storage—into a series of bytes that saves the state of the object in an easily transmittable form.
Turns out the answer to this is to make use of the magic include_xxx? methods...
class BarSerializer < FooSerializer
  def include_this?; false; end
  def include_that?; false; end
end
This will make it only serialize "the_other"
Make the BarSerializer the parents class and put the method the_other in it. FooSerializer will inherits only the method and the attribute defined in BarSerializer.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With