Skip to content

foca/granola-rails

Folders and files

NameName
Last commit message
Last commit date

Latest commit

 

History

14 Commits
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 

Repository files navigation

Granola::Rails Build Status RubyGem

Integrate Granola into Rails' rendering.

Usage

Once you install it, you can just use render to use Granola serializers:

class UsersController < ApplicationController
  def show
    user = User.find(params[:id])
    render json: user
  end
end

This would infer a UserSerializer (in app/serializers/user_serializer.rb). You can pass any options to this method that you could pass to Granola::Rack#granola. For example, to use a different serializer:

class UsersController < ApplicationController
  def show
    user = User.find(params[:id])
    render json: user, with: DetailedUserSerializer
  end
end

Serialization formats

Any serialization format you add to Granola via Granola.render will be available to render through rails. For example:

# config/initializers/granola.rb
Granola.render :yaml, via: YAML.method(:dump), content_type: Mime[:yaml].to_s

# app/controllers/users_controller.rb
class UsersController < ApplicationController
  def show
    user = User.find(params[:id])

    respond_to do |format|
      format.json { render json: user }
      format.yaml { render yaml: user }
    end
  end
end

Rails Generators

This library provides a serializer generator:

$ rails generate serializer user
      create  app/serializers/user_serializer.rb
      invoke  test_unit
      create    test/serializers/user_serializer_test.rb

Installation

Add this line to your application's Gemfile:

gem 'granola-rails'

And then execute:

$ bundle

Or install it yourself as:

$ gem install granola-rails

License

The gem is available as open source under the terms of the MIT License. See the LICENSE for detjsonails.