It seems a solid API that returns JSON is almost a prerequisite for any new web app these days. Often these JSON data structures return nested associated data, composed from several models in the system. There has been some discussion this week around tools and approaches to building JSON data structures in a Ruby web app API.
Perhaps the biggest buzz this week has been around Jbuilder which DHH announced on Twitter. While the world doesn’t need another J_Anything_, it does provide a nice API that can be used stand alone from controllers or as a view template:
Jbuilder.encode do |json|
json.(@message, :created_at, :updated_at)
json.author do |json|
json.url url_for(@message.creator, format: :json)
… which produces:
"content": "<p>This is <i>serious</i> monkey business",
"name": "David H.",
"email_address": "'David Heinemeier Hansson' <firstname.lastname@example.org>",
Another promising gem is Boxer from the team at Gowalla. While tied more closely to ActiveRecord and Rails, Boxer lets you define multiple views for an object, allowing you to expose extended attributes, usually based on permissions:
Boxer.box(:user) do |box, user|
:name => user.name,
:age => user.age,
box.view(:full, :extends => :base) do
:email => user.email,
:is_private => user.private?,
Finally John Nunemaker shared his thoughts learned building the Gaug.es API on his popular Rails Tips blog. John uses the Presenter pattern to craft the JSON output.
For even more projects in this space, check out the JBuilder README which provides a list of resources at the bottom. The most mature of these looks to be RABL from Nathan Esquenazi.