JSON serialization for client-side apps, with multiple output formats. Ships with ActiveModel::Serializers and JSON-API 1.0 support out of the box.
If you're building a Rails project, take a look at ivy-serializers-rails instead.
Add this line to your application's Gemfile:
gem 'ivy-serializers'And then execute:
bundleOr install it yourself:
gem install ivy-serializersAssuming we have Post and Comment models:
class Post < ActiveRecord::Base
has_many :comments
end
class Comment < ActiveRecord::Base
belongs_to :post
endDefine a serializer in app/serializers/my_serializer.rb:
class MySerializer < Ivy::Serializers::Serializer
map Post do
attributes :title
has_many :comments
end
map Comment do
attributes :body
belongs_to :post
end
endNOTE: An id attribute is automatically defined for you. This is a consequence of supporting JSON-API, which requires all resources to have IDs.
The #belongs_to and #has_many methods support an optional :embed_in_root option, which will load the associated record into the root of the payload. For instance, if we wanted the list of comments to be included when fetching a post, we could define the has_many relationship like so:
map Post do
has_many :comments, :embed_in_root => true
endThe same thing also works with belongs_to, so if we wanted to ensure the post was included when fetching a comment:
map Comment do
belongs_to :post, :embed_in_root => true
endThere is also support for polymorphic associations. To use it, pass the :polymorphic => true option to the #belongs_to or #has_many methods:
map Post do
has_many :replies, :polymorphic => true
end
map Comment do
belongs_to :commentable, :polymorphic => true
endBy default, attributes are mapped directly to methods on the record being serialized. So defining:
map Post do
attributes :title
endwill read title from the post and write it into the hash under the :title key. If you want to customize the value, you can use the #attribute method instead, and pass it a block:
map Post do
attribute(:title) { |post| post.headline }
endIn the above example, we read the headline attribute from the post and write it into the payload under the :title key.
- Fork it ( https://github.com/[my-github-username]/ivy-serializers/fork )
- Create your feature branch (
git checkout -b my-new-feature) - Commit your changes (
git commit -am 'Add some feature') - Push to the branch (
git push origin my-new-feature) - Create a new Pull Request