Skip to content

Instantly share code, notes, and snippets.

@pauldix
Created February 20, 2009 19:51
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 pauldix/67662 to your computer and use it in GitHub Desktop.
Save pauldix/67662 to your computer and use it in GitHub Desktop.
# A code snippet that takes a hash and recursively converts it to an object
# that you call methods on instead of hash accessors. So
# h = {:foo => "bar}
# h[:foo] # => "bar"
# h = Hashit.new(h)
# h.foo # => "bar"
# a modified version of the hash mapping stuff here:
# http://pullmonkey.com/2008/1/6/convert-a-ruby-hash-into-a-class-object
class Hashit
def initialize(hash)
hash.each do |k,v|
v = hash_children(v)
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
def hash_children(object)
if object.is_a?(Hash)
Hashit.new(object)
elsif object.is_a?(Array)
object.map {|o| hash_children(o)}
else
object
end
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment