public
Created

Hash with dot notations

  • Download Gist
with_dot_notation.rb
Ruby
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40
class HashWithDotNotation < Hash
 
def initialize(constructor = {})
if constructor.is_a?(Hash)
super()
self.replace(constructor)
else
super(constructor)
end
end
 
def method_missing_with_dot_notation_lookup(*args)
if self.has_key?(args[0])
rvalue = self.fetch(args[0])
rvalue = rvalue.with_dot_notation if rvalue.is_a?(Hash)
rvalue.map!{|e| e.is_a?(Hash) ? e.with_dot_notation : e } if rvalue.is_a?(Array)
rvalue
else
self.method_missing_with_out_dot_notation_lookup(*args)
end
end
alias_method_chain :method_missing, :dot_notation_lookup
end
 
 
class Hash #:nodoc:
def with_dot_notation
hash = HashWithDotNotation.new(self)
hash.default = self.default
hash
end
def with_dot_notation!
self.replace self.with_dot_notation
end
end

Please sign in to comment on this gist.

Something went wrong with that request. Please try again.