Skip to content

Template registration

nesquena edited this page Feb 12, 2012 · 1 revision

RABL has support for Rails, Padrino, Sinatra and any Tilt-based templating framework (i.e Renee). These template handlers live in template.rb. Notice there is one for Tilt, one for Rails 2 and one for Rails 3.

The Tilt one, which is the most straightforward, looks like:

if defined?(Tilt)
  class RablTemplate < Tilt::Template
    def initialize_engine
      return if defined?(::Rabl)
      require_template_library 'rabl'
    end

    def prepare
      options = @options.merge(:format => @options[:format], :source_location => file)
      @engine = ::Rabl::Engine.new(data, options)
    end

    def evaluate(scope, locals, &block)
      @engine.render(scope, locals, &block)
    end
  end

  Tilt.register 'rabl', RablTemplate
end

This reveals how RABL template construction works. First you construct a Rabl::Engine, which takes the template instructions (i.e attributes, child, node) used to compose a response:

instructions = "object @post\nattribute :name"
options = { :format => :json }
@engine = ::Rabl::Engine.new(instructions, options)

Once you have an engine, created based on the object rules passed into the constructor. You can then render any object using those rules by invoking render with the parent scope and the object data:

@post = Post.new(...)
# scope = request context with access to instance variables
locals = { :object => @post } 
@engine.render(scope, locals)

That is at a high-level how RABL responses are generated.