The grape-with-roar project deployed here on heroku.
Add the grape
, roar
and grape-roar
gems to Gemfile.
gem 'grape'
gem 'roar'
gem 'grape-roar'
If you're upgrading from an older version of this gem, please see UPGRADING.
class API < Grape::API
format :json
formatter :json, Grape::Formatter::Roar
end
Include Grape::Roar::Representer into a representer module after any Roar mixins, then use Grape's present
keyword.
module ProductRepresenter
include Roar::JSON
include Roar::Hypermedia
include Grape::Roar::Representer
property :title
property :id
end
get 'product/:id' do
present Product.find(params[:id]), with: ProductRepresenter
end
Presenting collections works the same way. The following example returns an embedded set of products in the HAL Hypermedia format.
module ProductsRepresenter
include Roar::JSON::HAL
include Roar::Hypermedia
include Grape::Roar::Representer
collection :entries, extend: ProductRepresenter, as: :products, embedded: true
end
get 'products' do
present Product.all, with: ProductsRepresenter
end
The formatter invokes to_json
on presented objects and provides access to the requesting environment via the env
option. The following example renders a full request URL in a representer.
module ProductRepresenter
include Roar::JSON
include Roar::Hypermedia
include Grape::Roar::Representer
link :self do |opts|
request = Grape::Request.new(opts[:env])
"#{request.url}"
end
end
If you prefer to use a decorator class instead of modules.
class ProductRepresenter < Grape::Roar::Decorator
include Roar::JSON
include Roar::Hypermedia
link :self do |opts|
"#{request(opts).url}/#{represented.id}"
end
private
def request(opts)
Grape::Request.new(opts[:env])
end
end
get 'products' do
present Product.all, with: ProductsRepresenter
end
See CONTRIBUTING.
MIT License, see LICENSE for details.
(c) 2012-2014 Daniel Doubrovkine & Contributors, Artsy