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.content format_content(@message.content)
  json.(@message, :created_at, :updated_at)

  json.author do |json|
    json.name @message.creator.name.familiar
    json.email_address @message.creator.email_address_with_name
    json.url url_for(@message.creator, format: :json)
  end

  if current_user.admin?
    json.visitors calculate_visitors(@message)
  end

  ...
end

… which produces:

{ 
  "content": "<p>This is <i>serious</i> monkey business",
  "created_at": "2011-10-29T20:45:28-05:00",
  "updated_at": "2011-10-29T20:45:28-05:00",

  "author": {
    "name": "David H.",
    "email_address": "'David Heinemeier Hansson' <david@heinemeierhansson.com>",
    "url": "http://example.com/users/1-david.json"
  },

  "visitors": 15

  ...
}

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|
  box.view(:base) do
    {
      :name => user.name,
      :age  => user.age,
    }
  end

  box.view(:full, :extends => :base) do
    {
      :email      => user.email,
      :is_private => user.private?,
    }
  end
end

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.


Have comments? Send a tweet to @TheChangelog on Twitter.

Subscribe to The Changelog Weekly – our weekly email covering everything that hits our open source radar.