method_missing 的多个参数
我在模型中实现了以下 method_missing
代码:
# 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
是一个全局对象。请注意,这是类的method_missing
,而不是实例。
我在脚本/控制台中尝试了以下操作:
>> $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
是否有一些我在这里遗漏的非常明显的东西?我正在 Rails 2.3.8 和 jRuby 上运行它,如果这有什么不同的话。
编辑:这让我更加困惑:
>> Thought.send(:my_thoughts, 'bob', 5, 5)
ArgumentError: wrong # of arguments(3 for 2)
from [filepath]:50:in `method_missing'
from (irb):23
用整数以外的东西替换第二个参数似乎可行,但当然参数应该是整数......我现在怀疑有问题jRuby 或我集成到其中的 Java 类。
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)
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.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
您提供的代码在 ruby-1.8.7 和 ruby-1.9.2 上都适用,所以听起来您使用的 jRuby 版本存在错误。为了完整起见,这是我运行的代码:
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:
事实证明,问题实际上出在我上面省略的部分:
显然它定义了一个方法“collect”,它接受两个参数,这让我误以为它是可枚举的……想想看。
Turns out the problem was actually with the part I omitted from above:
Apparently it had a method "collect" defined which took 2 arguments, which tricked me into thinking it was Enumerable...go figure.