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

how to optionally include / delete values in an Active Model Serializer 0.10 class


I have the folowing ASM 0.10 :

class UserMicroSerializer < ActiveModel::Serializer
  attributes :id, :name, :is_friend


  def is_friend
    @instance_options[:is_friend]
  end
end

but would also like to support not having the is_friend attribute.

I have tried various things like:

class UserMicroSerializer < ActiveModel::Serializer
  attributes :id, :name
  if @instance_options[:is_friend]
    attributes :is_friend
  end


  def is_friend
    @instance_options[:is_friend]
  end
end

but get error msg:

NoMethodError: undefined method `[]' for nil:NilClass

How would I make the @instane_options conditionally include is_friend?


Solution

  • If you can conditionally use a different serializer in the controller then you may be able to do this

    class SimpleUserMicroSerializer < ActiveModel::Serializer
      attributes :id, :name
    end
    

    By subclassing the simple serializer, you don't have much code overlap

    class UserMicroSerializer < SimpleUserMicroSerializer
      attributes :is_friend
    
      def is_friend
        @instance_options[:is_friend]
      end
    
    end