Created
November 26, 2014 21:06
-
-
Save bethesque/ce08e1cdf36f43ec0a91 to your computer and use it in GitHub Desktop.
Using Representable to convert one hash to another hash without having to create intermediate classes
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
require 'representable' | |
require 'representable/json' | |
require 'ostruct' | |
require 'json' | |
require 'hashie' | |
json = { | |
person: { | |
name: 'Beth', | |
surname: 'Someone' | |
}, | |
address: { | |
address_line_1: '999 Some Street' | |
} | |
}.to_json | |
class Representor < Representable::Decorator | |
include Representable::JSON | |
property :person, class: Hashie::Mash do | |
property :firstname, as: :name | |
property :lastname, as: :surname | |
end | |
property :address, class: Hashie::Mash do | |
property :street, as: :address_line_1 | |
end | |
end | |
target = Hashie::Mash.new | |
Representor.new(target).from_json(json) | |
puts target.to_hash | |
# => {"person"=>{"firstname"=>"Beth", "lastname"=>"Someone"}, "address"=>{"street"=>"999 Some Street"}} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Using OpenStruct instead of Hashie::Mash gives you