'ActiveModel serializer inheritance

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.



Solution 1:[1]

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"

Solution 2:[2]

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.

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1
Solution 2