Multiple arguments for method_missing
I have the following method_missing
code implemented in a model:
# class Thought
def self.method_missing(method_id, *arguments, &block)
if $CLIENT.respond_to?(method_id)
$CLIENT.send(method_id, *arguments, &block)
# Do some stuff with it
else
super
end
end
$CLIENT
is a global object. Note that this is method_missing
for the class, not the instance.
I tried the following in script/console:
>> $CLIENT.respond_to?(:my_thoughts)
=> true
>> $CLIENT.send(:my_thoughts, 'bob', 5)
=> #<#<Class:01xe229be>:0x241391>
>> Thought.send(:my_thoughts, 'bob', 5)
ArgumentError: wrong # of arguments(1 for 2)
from [filepath]:50:in `method_missing'
from (irb):4
Is there something painfully obvious I'm missing here? I'm running this on Rails 2.3.8 and jRuby if that makes a difference.
Edit: This confuses me even more:
>> Thought.send(:my_thoughts, 'bob', 5, 5)
ArgumentError: wrong # of arguments(3 for 2)
开发者_如何学JAVA from [filepath]:50:in `method_missing'
from (irb):23
Replacing the second argument with something other than an Integer appears to work, but of course the argument is supposed to be an Integer... I am now suspecting a problem in either jRuby or the Java classes I integrated into this.
The code you provided works for me on both ruby-1.8.7 as well as ruby-1.9.2, so it sounds like there's a bug in the version of jRuby you're using. For completeness, this is the code I ran:
#!/usr/bin/env ruby
class Client
def my_thoughts(person, val)
puts "#{person} is thinking #{val}"
end
end
$CLIENT = Client.new
class Thought
def self.method_missing(method_id, *arguments, &block)
if $CLIENT.respond_to?(method_id)
$CLIENT.send(method_id, *arguments, &block)
# Do some stuff with it
else
super
end
end
end
Thought.send(:my_thoughts, 'bob', 5)
Turns out the problem was actually with the part I omitted from above:
$CLIENT.send(method_id, *arguments, &block).collect |item|
Apparently it had a method "collect" defined which took 2 arguments, which tricked me into thinking it was Enumerable...go figure.
精彩评论