Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 785
patrick Avatar asked Feb 25 '15 02:02

patrick


People also ask

What is ActiveModel serializer?

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.

What does a serializer do in Ruby?

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.

What is serializer in backend?

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.


2 Answers

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"

like image 165
patrick Avatar answered Oct 09 '22 05:10

patrick


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.

like image 24
Passalini Avatar answered Oct 09 '22 06:10

Passalini