Created
January 17, 2012 22:55
-
-
Save lytithwyn/1629609 to your computer and use it in GitHub Desktop.
Convert a Hash to an object recursively
This file contains 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
# 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