Skip to content
This repository

Use rabl with grape

branch: master
README.md

Grape::Rabl

Use Rabl templates in Grape!

Build Status Dependency Status Code Climate Coverage Status Gem Version

Installation

Add the grape and grape-rabl gems to Gemfile.

gem 'grape'
gem 'grape-rabl'

And then execute:

$ bundle

Usage

Require grape-rabl

# config.ru
require 'grape/rabl'

Setup view root directory

# config.ru
require 'grape/rabl'

use Rack::Config do |env|
  env['api.tilt.root'] = '/path/to/view/root/directory'
end

Tell your API to use Grape::Formatter::Rabl

class API < Grape::API
  format :json
  formatter :json, Grape::Formatter::Rabl
end

Use rabl templates conditionally

Add the template name to the API options.

get "/user/:id", :rabl => "user.rabl" do
  @user = User.find(params[:id])
end

You can use instance variables in the Rabl template.

object @user => :user
attributes :name, :email

child @project => :project do
  attributes :name
end

Use rabl layout

Gape-rabl first looks for a layout file in #{env['api.tilt.root']}/layouts/application.rabl.

You can override the default layout conventions:

# config.ru
require 'grape/rabl'

use Rack::Config do |env|
  env['api.tilt.root'] = '/path/to/view/root/directory'
  env['api.tilt.layout'] = 'layouts/another'
end

You can omit .rabl

The following are identical.

get "/home", :rabl => "view"
get "/home", :rabl => "view.rabl"

Example

# config.ru
require 'grape/rabl'

use Rack::Config do |env|
  env['api.tilt.root'] = '/path/to/view/root/directory'
end

class UserAPI < Grape::API
  format :json
  formatter :json, Grape::Formatter::Rabl

  # use rabl with 'user.rabl' template
  get '/user/:id', :rabl => 'user' do
    @user = User.find(params[:id])
  end

  # do not use rabl, fallback to the defalt Grape JSON formatter
  get '/users' do
    User.all
  end
end
# user.rabl
object @user => :user

attributes :name

Usage with rails

Create grape application

# app/api/user.rb
class MyAPI < Grape::API
  format :json
  formatter :json, Grape::Formatter::Rabl
  get '/user/:id', :rabl => "user" do
    @user = User.find(params[:id])
  end
end
# app/views/api/user.rabl
object @user => :user

Edit your config/application.rb and add view path

# application.rb
class Application < Rails::Application
  config.middleware.use(Rack::Config) do |env|
    env['api.tilt.root'] = Rails.root.join "app", "views", "api"
  end
end

Mount application to rails router

# routes.rb
GrapeExampleRails::Application.routes.draw do
  mount MyAPI , :at => "/api"
end

Specs

See "Writing Tests" in https://github.com/intridea/grape README.

Enjoy :)

Contributing

  1. Fork it
  2. Create your feature branch (git checkout -b my-new-feature)
  3. Commit your changes (git commit -am 'Added some feature')
  4. Push to the branch (git push origin my-new-feature)
  5. Create new Pull Request

Bitdeli Badge

Something went wrong with that request. Please try again.