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
endInclude 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
endget 'product/:id' do
present Product.find(params[:id]), with: ProductRepresenter
endPresenting 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
endget 'products' do
present Product.all, with: ProductsRepresenter
endThe 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
endIf 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
endget 'products' do
present Product.all, with: ProductsRepresenter
endSee CONTRIBUTING.
MIT License, see LICENSE for details.
(c) 2012-2014 Daniel Doubrovkine & Contributors, Artsy