Skip to content

Instantly share code, notes, and snippets.

@bethesque
Created November 26, 2014 21:06
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save bethesque/ce08e1cdf36f43ec0a91 to your computer and use it in GitHub Desktop.
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
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"}}
@bethesque
Copy link
Author

Using OpenStruct instead of Hashie::Mash gives you

{:person=>#<OpenStruct firstname="Beth", lastname="Skurrie">, 
 :address=>#<OpenStruct street="999 Some Street">}

@bethesque
Copy link
Author

Bethtest comment.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment