8000 GitHub - OutlawAndy/attr_serializer: easy JSON serialization for ActiveRecord models
[go: up one dir, main page]
More Web Proxy on the site http://driver.im/
Skip to content

OutlawAndy/attr_serializer

Folders and files

NameName
Last commit message
Last commit date

Latest commit

 

History

9 Commits
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 

Repository files navigation

AttrSerializer Gem Version

easy JSON serialization for ActiveRecord models

Installation

Add this line to your application's Gemfile

gem 'attr_serializer'

Or install it yourself

$ gem install attr_serializer

Usage

in your ActiveRecord models

class User < ActiveRecord::Base
  attr_serializer :id, :name
end

Now, whenever to_json is called on an instance or collection of User objects, only id & name will be serialized

class UsersController < ApplicationController

  def show
    render json: User.find(123)
  end

end
{"id": 123, "name": "Bob Jones"}

Any attribute or method name can be supplied to attr_serializer

class User < ActiveRecord::Base
  attr_serializer :id, :name, :some_data

  def some_data
    "not in database"
  end
end
{"id": 123, "name": "Bob Jones", "some_data": "not in database"}

You may also specify alternate keys for the resulting json by passing a hash as the last argument to attr_serializer

class User < ActiveRecord::Base
  attr_serializer :id, :name, someData: :some_data

  def some_data
    "not in database"
  end
end
{"id": 123, "name": "Bob Jones", "someData": "not in database"}

attr_serializer is also inherited accross STI models

class Admin < User
  attr_serializer :admin_stuff

  def admin_stuff
    "super important"
  end
end
Admin.first.to_json
#=> "{\"id\": 124, \"name\": \"Admin Bob\", \"someData\": \"not in database\", \"admin_stuff\": \"super important\"}"

Contributing

Bug reports and pull requests are welcome on GitHub at https://github.com/OutlawAndy/attr_serializer.

License

The gem is available as open source under the terms of the MIT License.

About

easy JSON serialization for ActiveRecord models

Topics

Resources

License

Stars

Watchers

Forks

Releases

No releases published

Packages

No packages published

Contributors 2

  •  
  •  
0