No description
Find a file
2013-04-04 20:15:16 +01:00
lib Initial commit 2013-04-04 20:10:51 +01:00
spec Initial commit 2013-04-04 20:10:51 +01:00
.DS_Store Initial commit 2013-04-04 20:10:51 +01:00
.gitignore Initial commit 2013-04-02 09:41:53 -07:00
Gemfile Initial commit 2013-04-04 20:10:51 +01:00
Gemfile.lock Initial commit 2013-04-04 20:10:51 +01:00
grape-active_model_serializers.gemspec Initial commit 2013-04-04 20:10:51 +01:00
LICENSE Initial commit 2013-04-04 20:10:51 +01:00
Rakefile Initial commit 2013-04-04 20:10:51 +01:00
README.md Initial commit 2013-04-04 20:10:51 +01:00

Grape::ActiveModelSerializers

Use active_model_serializers with Grape!

Build Status Dependency Status

Installation

Add the grape and grape-active_model_serializers gems to Gemfile.

gem 'grape'
gem 'grape-active_model_serializers'

And then execute:

bundle

Usage

Require grape-active_model_serializers

# config.ru
require 'grape/active_model_serializers'

Tell your API to use Grape::Formatter::ActiveModelSerializers

class API < Grape::API
  format :json
  formatter :json, Grape::Formatter::ActiveModelSerializers
end

Writing serializers

See active_model_serializers

Serializers are inferred by active_record model names

grape-active_model_serializers will search for serializers for the objects returned by your grape API.

Serializer

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.

Disabling serializer inferrence

You can turn off serializer inferrence.

Grape::Formatter::ActiveModelSerializers.infer_serializers = false

Manually specifying a serializer

Serializers can be specified at a route level by with the serializer option. A serializer can be specified with its class name or by name as string/symbol. The following are equivalent:

get "/home", :serializer => HomeSerializer
...
get "/home", :serializer => "home"

get "/home", :serializer => :home

Example

# user.rb
class User
  include ActiveModel::SerializerSupport

  attributes :first_name, :last_name, :email
end
# user_serializer.rb
class UserSerializer < ActiveModel::Serializer
  attributes :first_name, :last_name
end

Rspec

See "Writing Tests" in https://github.com/intridea/grape.

Enjoy :)

Contributing

  1. Fork it
  2. Create your feature branch (git checkout -b my-new-feature)
  3. Commit your changes (git commit -am 'Added some feature')
  4. Push to the branch (git push origin my-new-feature)
  5. Create new Pull Request

Thanks to

The developers and maintainers of: active_model_serializers Grape!

Structured and based upon Grape.