[英]Multiple arguments for 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
用除Integer以外的其他内容替换第二个参数似乎可以工作,但是当然该参数应该是Integer ...我现在怀疑jRuby或集成到其中的Java类中的问题。
您提供的代码在ruby-1.8.7和ruby-1.9.2上都对我有效,因此听起来您正在使用的jRuby版本中存在一个错误。 为了完整性,这是我运行的代码:
#!/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)
事实证明问题实际上是我从上面省略的部分:
$CLIENT.send(method_id, *arguments, &block).collect |item|
显然,它定义了一个方法“ collect”,该方法带有2个参数,这使我误以为它是Enumerable ... go值。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.