This gem has the function of adapt the Active Model Serializers to work in Sinatra from a more practical way with models.
If do you use everything at the default, just require sinatra_active_model_serializers
for serializers work correctly the a json response.
Ruby 1.9.2 or greater, Sinatra 1.4.5 or greater and Sinatra Contrib 1.4.2 or greater.
gem install sinatra-active-model-serializers
or with bundler
# Gemfile
source 'http://rubygems.org'
gem 'sinatra', '1.4.6'
gem 'sinatra-contrib', '1.4.6'
gem 'sinatra-active-model-serializers', '0.2.0'
It's very easy. Look at the example:
require 'rubygems'
require 'bundler'
Bundler.require :default
Dir['./app/models/**/*.rb'].each { |file| require file }
class App < Sinatra::Base
get '/' do
json Test.first
end
end
This attribute is an object, all inserted configuration this object it will be passed on to Active Model Serializers, eg.
set :active_model_serializers, { root: false }
By default, path is app/serializers
. If you need a different path you can set your path, eg.
set :serializers_path, './whatever_path/serializers'
or you can disable auto require
set :serializers_path, false
When you return a json, you can send a the second parameter. This the second parameter is an object. This object may contain new configurations to assign to the Active Model Serializers or to rewrite any already set by default, eg.
get '/' do
json Resource.first, { root: false }
end
get '/' do
json Resource.first, { scope: self }
end
If you wish to use an another serializer than the default, you can explicitly pass it through the renderer
- For a resource:
json Resource.first, { serializer: ResourcePreviewSerializer }
- For an array resource:
Use the default ArraySerializer
, which will use each_serializer
to
serialize each element.
json @resources, { each_serializer: ResourcePreviewSerializer }