Reputation: 13012
i am trying to write a method_missing method, so that when i run a method it must hit the hash and look at the keys, if it finds a match to return the value. and continue. the hash is populated from a sql query that i wrote so the values are never constant.
an example would be like
@month_id.number_of_white_envelopes_made
in the hash
@data_hash[number_of_white_envelopes_made] => 1
so @month_id will return 1. i have never worked with it before, not much material out there using hashes as the fall back with method missing
EDIT: sorry i forgot to say if it doesnt find the method in the hash then it can continue down to no method error
EDIT: alright so i was hacking away and this is what i have come up with
def method_missing(method)
if @data_hash.has_key? method.to_sym
return @data_hash[method]
else
super
end
end
is there a better way?
Upvotes: 0
Views: 2217
Reputation: 27813
The shortest is
class Hash
def method_missing(sym,*)
fetch(sym){fetch(sym.to_s){super}}
end
end
which first tries hash[:key]
and then hash["key"]
Upvotes: 2
Reputation: 6562
What about something like:
def method_missing(method_sym, *arguments, &block)
if @data_hash.include? method_sym
@data_hash[method_sym]
else
super
end
end
And always remember to add the corresponding respond_to? to your object:
def respond_to?(method_sym, include_private = false)
if @data_hash.include? method_sym
true
else
super
end
end
Upvotes: 6