Skip to content

Instantly share code, notes, and snippets.

@davidlee
Created September 4, 2009 01:33
Show Gist options
  • Save davidlee/180677 to your computer and use it in GitHub Desktop.
Save davidlee/180677 to your computer and use it in GitHub Desktop.
class Hash
def with_slutty_access
HashWithSluttyAccess.new(self)
end
end
# as per HashWithIndifferentAccess, with some OpenStruct flavour
class HashWithSluttyAccess < HashWithIndifferentAccess
def dup
HashWithSluttyAccess.new(self)
end
def reverse_merge(other_hash)
super other_hash.with_slutty_access
end
def method_missing(method_name, *args)
if args.empty? && self[method_name]
self[method_name]
elsif method_name.to_s[/^(.*)=$/]
self[$1] = args.first
else
super method_name, *args
end
end
protected
def convert_value(value)
case value
when Hash
value.with_slutty_access
when Array
value.collect { |e| e.is_a?(Hash) ? e.with_slutty_access : e }
else
value
end
end
end
# >> hash = {:a => {"b" => [{:c => 123}]}}.with_slutty_access
# => {"a"=>{"b"=>[{"c"=>123}]}}
# >> hash.a.b[0].c
# => 123
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment