Created
May 7, 2013 12:52
-
-
Save janx/5532329 to your computer and use it in GitHub Desktop.
Monkey patch hash so it behaves like OpenStruct
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
class Hash | |
alias :__values :values | |
def values | |
self["values"] || __values | |
end | |
alias :__method_missing :method_missing | |
def method_missing(name, *args, &block) | |
if args.empty? | |
self[name.to_s] || self[name] | |
elsif args.size == 1 && name =~ /=$/ | |
class <<self; self; end.send :attr_accessor, name[0..-2] | |
self.send name, args.first | |
else | |
__method_missing(name, *args, &block) | |
end | |
end | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment