Search code examples
ruby-on-railsactive-model-serializers

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

  • 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"