Last active
December 15, 2015 10:16
-
-
Save dreamingechoes/aec6542f2f5d1ade510b to your computer and use it in GitHub Desktop.
Convert ruby hashes into objects.
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
class Hashit | |
def initialize(hash) | |
hash.each do |k,v| | |
self.instance_variable_set("@#{k}", v.is_a?(Hash) ? Hashit.new(v) : v) | |
self.class.send(:define_method, k, proc{self.instance_variable_get("@#{k}")}) | |
self.class.send(:define_method, "#{k}=", proc{|v| self.instance_variable_set("@#{k}", v)}) | |
end | |
end | |
end | |
h = Hashit.new({a: '123r', b: {c: 'sdvs'}}) | |
# h.a => '123r' | |
# h.b.c => 'sdvs' |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment