josevalim/active_model_serializers — pull request #87 by dvdplm (2012-07-06 13:42:11+00:00)
Title: Alternative serialization configuration: hash&lambdas

For serialization needs where the JSON keys and values differ a lot from the raw model, using the current mix of `attribute :something, key: :something_else` and `attributes :thing, :thang, :thong` led to a quite ugly looking serializer with lots and lots of instance methods. This fork implements an alternative syntax, while maintaining backwards compatibility with the previous one.

Instead of this:

```ruby
class CommentSerializer < ActiveModel::Serializer
attributes :text, :author_id, :author_username, :created_at, :updated_at, :likes_count, :comments_count, :author_avatar_image_url

attribute :item_id, key: :post_id
attribute :id, key: :comment_id

def author_username
object.author.username
end

def comments_count
object.item.comments.count
end

def author_avatar_image_url
object.author.avatar.try( :image_url, :pinky )
end
end
```

...we can now do this:

```ruby
class CommentSerializer < ActiveModel::Serializer
attributes_hash text: nil,
post_id: :item_id,
comment_id: :id,
author_id: nil,
author_username: ->{ author.username },

# Timestamps
created_at: nil,
updated_at: nil,

# Counters
likes_count: nil,
comments_count: ->{ item.comments.count },

# Resources
author_avatar_image_url: ->{ author.avatar.try( :image_url, :pinky ) }

end
```

Thoughts?