0.0
No commit activity in last 3 years
No release in over 3 years
Granola provides a simple and fast API to serialize objects into multiple formats. Granola::Rails just simplifies using Granola from Rails apps.
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
 Dependencies

Runtime

< 6, >= 4.0
~> 1.0
 Project Readme

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.