If you are building an API application with Ruby on Rails, you will notice that
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:
@post = post
Then in a controller, I would have something like:
post = Post.find(params[:id])
render json: PostSerializer.new(post).serialize.to_json