rails-api/active_model_serializers — pull request #577 by Arjeno (2014-06-24 15:11:25+00:00)
Title: Context for ArraySerializer and HasOne associations

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)__
```ruby
class OrderSerializer < ActiveModel::Serializer
has_many :plan_items
end
class PlanItemSerializer < ActiveModel::Serializer
has_one :order
end
```

__Example after (new)__
```ruby
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:
```ruby
def in_context?(object=nil)
if object.present?
@context.kind_of?(object)
else
@context.present?
end
end
```

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