Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

Already on GitHub? Sign in to your account

Context for ArraySerializer and HasOne associations #577

Closed
wants to merge 1 commit into
from

Conversation

Projects
None yet
2 participants

Arjeno commented Jun 24, 2014

This pull request adds context to serializers. This means it's possible to differ a serialized response based on context. For example include or exclude certain associations when rendering in an array context. Or simplify responses when embedded in another serializer.

Example before (infinite loop)

class OrderSerializer < ActiveModel::Serializer
  has_many :plan_items
end
class PlanItemSerializer < ActiveModel::Serializer
  has_one :order
end

Example after (new)

class OrderSerializer < ActiveModel::Serializer
  has_many :plan_items

  def filter(keys)
    keys.delete(:plan_items) if @context.kind_of?(PlanItemSerializer)
    keys
  end
end
class PlanItemSerializer < ActiveModel::Serializer
  has_one :order
end

Or you could add a handy method to your serializer for checking context:

def in_context?(object=nil)
  if object.present?
    @context.kind_of?(object)
  else
    @context.present?
  end
end

I can add the above method to the pull request if anyone wants it.

Contributor

steveklabnik commented Jul 28, 2014

I'm not interested in changing the interface of AMS significantly in 0.9. I'd be interested in having something like this in 0.10, though. Thank you!

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment