If you are building an API application with Ruby on Rails, you will notice that
the jbuilder
gem is suggested in the default Gemfile
. Jbuilder allows you to
create JSON using a builder domain specific language. Some people prefer
ActiveModel::Serializers
which has its own DSL, is more declarative and
handles structural conventions for you. This is convenient if you want your API
to conform to the JSON API specification or a custom format.
While these gems (and others) each have their trade-offs, in some projects, they are more of a hindrance than help. I have another serialization strategy for these cases.
The Ruby standard library supports encoding primitives to JSON and ActiveSupport adds a layer on top of that to allow serialization of any Ruby object by first serializing it to a Hash. In my code, I build a hash directly:
class PostSerializer
def initialize(post)
@post = post
end
def serialize
{
title: post.title,
author: post.author
}
end
private
attr_reader :post
end
Then in a controller, I would have something like:
def show
post = Post.find(params[:id])
render json: PostSerializer.new(post).serialize.to_json
end