Skip to content

Instantly share code, notes, and snippets.

@rbarazi
Created June 10, 2010 16:43
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 rbarazi/433275 to your computer and use it in GitHub Desktop.
Save rbarazi/433275 to your computer and use it in GitHub Desktop.
Hash with dot notations
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
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment