Skip to content

Instantly share code, notes, and snippets.

@lytithwyn
Created January 17, 2012 22:55
Show Gist options
  • Save lytithwyn/1629609 to your computer and use it in GitHub Desktop.
Save lytithwyn/1629609 to your computer and use it in GitHub Desktop.
Convert a Hash to an object recursively
# modified from http://pullmonkey.com/2008/01/06/convert-a-ruby-hash-into-a-class-object/
class ObjectFromHash
def initialize(hash)
hash.each do |k,v|
# check to see if this value is a hash too
if v.class.name == "Hash"
v = ObjectFromHash.new(v)
end
self.instance_variable_set("@#{k}", v) ## create and initialize an instance variable for this key/value pair
self.class.send(:define_method, k, proc{self.instance_variable_get("@#{k}")}) ## create the getter that returns the instance variable
self.class.send(:define_method, "#{k}=", proc{|v| self.instance_variable_set("@#{k}", v)}) ## create the setter that sets the instance variable
end
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment