Project

greenin

0.0
No commit activity in last 3 years
No release in over 3 years
Describe your Grape Entities in Rails Active Record models
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
 Dependencies

Development

>= 1.6
>= 0
~> 0.11.0
~> 0.4.4
~> 10.0
~> 3.2.0
~> 1.3.10

Runtime

 Project Readme

Greenin

Gem Version Build Status Code Climate Test Coverage Dependency Status

Describe your Grape Entities in Rails Active Record models

Installation

Add this line to your application's Gemfile:

gem 'greenin'

or

gem 'greenin', github: 'itbeaver/greenin'

And then execute:

$ bundle

Or install it yourself as:

$ gem install greenin

Then run

$ rails g greenin:install

This generator creates an initializer with settings at config/initializers/greenin_initializer.rb. You can change method name and class name:

Greenin.setup do |config|
  config.entity_method_name = 'entity'
  config.entity_class_name = 'Entity'
end

Usage

Example describtion in Post model:

class Post < ActiveRecord::Base

  # ...

  class Entity < Grape::Entity
    format_with(:unix) { |dt| dt.to_i }
    root 'posts'

    expose :id
    with_options(format_with: :unix) do
      expose :created_at
      expose :updated_at
    end
    expose :title
    expose :description
  end

end

This gem add methods to your ActiveRecord models that call Entity.represent(self, args), so, you can call entity like that:

Post::Entity == Post.entity
# => true

Post.all.entity
# => {"posts"=>[#<Post::Entity:0x007ff0880d7d18
#                @object=#<Post id: 1, title: "Some title", created_at: "2015-02-27 17:48:07",
#                         updated_at: "2015-02-27 17:48:07">, @options={:collection=>true}>, ...]}

Post.all.entity.to_json
# => {"posts":[{"title":"Some title"},{"title":"Some title"},{"title":"Some title"}]}

Post.all.entity(root: 'myposts').to_json
# => {"myposts":[{"title":"Some title"},{"title":"Some title"},{"title":"Some title"}]}

Post.all.entity(root: 'myposts').to_json == Post::Entity.represent(Post.all, root: 'myposts').to_json
# => true

Post.first.entity.to_json
# => {"post":[{"title":"Some title"}]}

Post.first.entity(root: false).to_json
# => {"title":"Some title"}

In grape controller using json formatter:

  get '/posts' do
    status 200
    present Post.all.entity
  end

Contributing

  1. Fork it ( https://github.com/itbeaver/greenin/fork )
  2. Create your feature branch (git checkout -b my-new-feature)
  3. Commit your changes (git commit -am 'Add some feature')
  4. Push to the branch (git push origin my-new-feature)
  5. Create a new Pull Request