Add the grape
and grape-rabl
gems to Gemfile.
gem 'grape', "~> 0.2.3"
gem 'grape-rabl'
And then execute:
$ bundle
# config.ru
require 'grape/rabl'
# config.ru
require 'grape/rabl'
use Rack::Config do |env|
env['api.tilt.root'] = '/path/to/view/root/directory'
end
class API < Grape::API
format :json
formatter :json, Grape::Formatter::Rabl
end
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
The following are identical.
get "/home", :rabl => "view"
get "/home", :rabl => "view.rabl"
# 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
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
See "Writing Tests" in https://github.com/intridea/grape.
Enjoy :)
- Fork it
- Create your feature branch (
git checkout -b my-new-feature
) - Commit your changes (
git commit -am 'Added some feature'
) - Push to the branch (
git push origin my-new-feature
) - Create new Pull Request