Skip to content
Alan Larkin edited this page Apr 12, 2014 · 13 revisions

Setting up RABL on Sinatra is easy. In fact it's as easy as 1..2..3

###Step 1. Install the gem

$ gem install sinatra

###Step 2.

Set up your sinatra app to support RABL:

# app.rb
require 'rubygems' 
require 'sinatra'
require 'rabl'
require 'active_support/core_ext'
require 'active_support/inflector'
require 'builder'

# Register RABL
Rabl.register!

# Render RABL
get "/" do
  @foo = # ...
  rabl :foo, :format => "json"
  # or render :rabl, :foo, :format => "json"
  # or Rabl::Renderer.json(@foo, 'path/foo/index', view_path: 'app/views')
end

Note that if your view templates are stored anywhere other than the views directory, you must tell Sinatra and/or RABL. If you are rendering your templates with Rabl::Renderer.json(...), you need to set the RABL view_paths config variable. If you are using either render :rabl... or rabl ..., you need to change the Sinatra views setting, or pass in a views local variable. Remember too that in the latter case the location of your template must be a symbol, not a string, e.g.

rabl :'foos/index', :format => "json"

###Step 3.

Now just add a template of type .rabl to match the template referenced in your route to be rendered. For instance, in this case the name of the template is views/foo.rabl

# views/foo.json.rabl

object @foo

# Declarations here

And you're done! Now that's what I call easy.