I’m trying to access a hash by using an regular class method like this:
aHash.key
But I get this error:
undefined method `key1′ for {:key1=>”value1″, :key2=>”value2″}:Hash
I defined a ‘method_missing’ in a Hash class as suggested here:
class Hash
def method_missing(method, *params)
method = method.to_sym
return self[method] if self.keys.collect(&:to_sym).include?(method)
super
end
end
I know for sure, that when I call ‘aHash.key’ it does not use the Hash I defined. If I look at one on my gems, it shows this:
require “activerecord-postgres-hstore/hash”
So I checked this file, and indeed they have implemented another hash. I believe I should add ‘method_missing’ in there but can it be done without modified the gem?
Maybe I’m not getting how class overloading works with ruby, so the answer might be something else.
Like SporkInventor said, what you are doing is very dangerous and bad practice, you shouldn’t patch Hash. Instead, like he said, use OpenStruct from Ruby’s standard library. If you need, change your code to wrap the Hash into an OpenStruct when returning it.
So if you really need to monkey-patch, rather monkey patch the method that is returning the hash to wrap the result in an OpenStruct, instead of patching Hash. Or if you need it to really be a Hash (obj.is_a? Hash #=> true) then create a subclass of hash with your method_missing implementation and then monkey-patch the method returning the Hash to return your OpenHash (or whatever you call it).
For (made up) example you have a Hstore class which has a method return_hash which returns the hash. Then patch it like this:
Monkey-patching standard library is very bad practice!