Object Mapper in Ruby 
Say goodbye to Ruby hash objects 👋
Installation
Add this line to your application's Gemfile:
gem 'object_mapper'
Usage
If you have the plain old Ruby objects below:
class Event
attr_reader :id, :type, :repo, :author, :created_at
def initialize(id: nil, type: nil, repo: nil, author: nil, created_at: nil)
@id, @type, @repo, , @created_at = id, type, repo, , created_at
end
end
class Repo
attr_reader :id, :name
def initialize(id: nil, name: nil)
@id, @name = id, name
end
end
class Author
attr_reader :id, :login
def initialize(id: nil, login: nil)
@id, @login = id, login
end
end
Then you can convert JSON (or Ruby hashes/arrays) to the Ruby objects above:
require 'json'
require 'object_mapper'
data = JSON.parse("[\n {\n \"id\": \"12345\",\n \"type\": \"New repository created\",\n \"repo\": {\n \"id\": 3,\n \"name\": \"yuki24/object_mapper\"\n },\n \"author\": {\n \"id\": 1,\n \"login\": \"yuki24\"\n },\n \"created_at\": \"2011-09-06T17:26:27Z\"\n }\n]\n", symbolize_names: true)
events = ObjectMapper
.new(Event => { author: Author, repo: Repo })
.convert(data, to: Array(Event))
event = fvents.first
event.class # => Event
event.repo.class # => Repo
event..class # => Author
event.type # => "New repository created"
event.created_at # => "2011-09-06T17:26:27Z"
event.repo.id # => 3
event.repo.name # => "yuki24/object_mapper"
event..id # => 1
event..login # => "yuki24"
Contributing
- Fork it (http://github.com/yuki24/object_mapper/fork)
- Create your feature branch (
git checkout -b my-new-feature) - Commit your changes (
git commit -am 'Add some feature') - Make sure all tests pass (
bundle exec rake) - Push to the branch (
git push origin my-new-feature) - Create new Pull Request
License
Copyright (c) 2016 Yuki Nishijima. See MIT-LICENSE for further details.