rails-api/active_model_serializers — pull request #498 by christhekeele (2014-01-27 21:00:54+00:00)
Title: Nested and listed predicates

Looking ahead to the 0.9 update I realized I'd have to rewrite some monkey patches I'm using to keep a simple feature I've hacked into my serializers. I thought I'd take the opportunity of the alpha/refactor to see if perhaps they belong in AMS proper.

This pull request does not rebase cleanly into the refactor branch, something I can tend to if the general concept is vetted.

It allows virtual attribute and inclusion/filter methods to behave differently depending on the context a serializer is invoked in, `nested?` from `ActiveModel::Serializer::Association` and `listed?` from `ActiveModel::ArraySerializer`. For example:

```ruby
class PostSerializer < ApplicaitonSerializer
attribute :title, :body, :published_at
has_one :author
has_many :comments

def include_author?
not nested?
end

def include_comments?
not listed?
end
end
```

This will not display the author of the post if serialized in a nested context, for example as a serialized user's `favorite_post`. It will also not display the post's comments if serialized as a group of posts, for example as a user's `publications`. `nested?` and `listed?` should only both be true when serializing `has_many` associations.

Since my API gets more verbose the more you drill down on a resource, this keeps me from needing up to 4 different classes in combination to handle the possible permutations, and could be a useful pattern to incorporate into AMS (YMMV). It also will play very nicely with the centralized `filter` method in the upcoming release, since attributes in these contexts tend to be included/excluded in batches.