argonaut icon indicating copy to clipboard operation
argonaut copied to clipboard

Lightweight JSON builder for Rails

h1. Argonaut is a lightweight JSON builder template handler for Rails

h2. Installing it

It's as easy as:

script/plugin install git://github.com/jbr/argonaut.git

h2. Usage

It's a whole lot like @.xml.builder@, only it's @.json.argonaut@. Make an appropriately named view, like @show.json.argonaut@ and put something in it like:

for idea in @ideas
  doc.ideas do |i|
    i.title idea.title
    for comment in idea.comments
      i.comments do |c|
        c.author comment.author.to_s
        c.text comment.text
      end
    end
  end
end

Which is identical to

{
  :ideas => @ideas.map do |idea|
    {
      :title => idea.title,
      :comments => idea.comments.map do |comment|
        {
          :author => comment.author.to_s,
          :text => comment.text
        }
      end
    }
  end
}.to_json
end

Just a little code kata, not really sure that the former is actually prettier.

h2. XML too

The name makes less sense and it's not really better than Builder, but you can do @.xml.argonaut@ as well now. It's the equivalent of calling @to_xml(:root => 'response')@ on the above hash. In theory, the same file could be used for @.xml.argonaut@ and @.json.argonaut@, but it's not obvious how to tell the template handler system to reuse a template. Maybe soon.