Use active_model_serializers with Grape!
- BREAKING Changes behaviour of root keys when serialising arrays. See Array roots
Add the grape
and grape-active_model_serializers
gems to Gemfile.
gem 'grape'
gem 'grape-active_model_serializers'
And then execute:
bundle
# config.ru
require 'grape/active_model_serializers'
class API < Grape::API
format :json
formatter :json, Grape::Formatter::ActiveModelSerializers
end
grape-active_model_serializers
will search for serializers for the objects returned by your grape API.
namespace :users do
get ":id" do
@user = User.find(params[:id])
end
end
In this case, as User objects are being returned, grape-active_model_serializers will look for a serializer named UserSerializer.
When serializing an array, the array root is set to the innermost namespace name if there is one, otherwise it is set to the route name (e.g. get 'name').
namespace :users do
get ":id" do
@user = User.find(params[:id])
end
end
# root = users
get "people" do
@user = User.all
end
# root = people
# Serializer options can be specified on routes or namespaces.
namespace 'foo', :serializer => :bar do
get "/" do
# will use "bar" serializer
end
# Options specified on a route or namespace override those of the containing namespace.
get "/home", :serializer => :home do
# will use "home" serializer
end
# All standard options for `ActiveModel::Serializers` are supported.
get "/fancy_homes", :root => 'world', :each_serializer => :fancy_homes
...
end
end
class User < ActiveRecord::Base
attr_accessor :first_name, :last_name, :password, :email
end
class UserSerializer < ActiveModel::Serializer
attributes :first_name, :last_name
end
class API < Grape::API
get("/home") do
User.new({first_name: 'JR', last_name: 'HE', email: 'contact@jrhe.co.uk'})
end
end
API.new.get "/home" # => '{:user=>{:first_name=>"JR", :last_name=>"HE"}}'
See "Writing Tests" in https://github.com/intridea/grape.
Enjoy :)
- Released on rubygems.org
- BREAKING Changes behaviour of root keys when serialising arrays. See Array roots
- 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
The developers and maintainers of: active_model_serializers Grape!
Structured and based upon grape-rabl.