2010-11-04 46 views
0

多个参数,我有以下的模型来实现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类中存在问题。

+0

感谢您的编辑 - 我想说,这不是整个故事。我测试了上面给出的代码,并且它工作正常。来自具有method_missing的文件的实际行50将显示很多。 – 2010-11-04 03:35:08

回答

0

原来,问题是实际上我从上面省略了一部分:定义历时2

$CLIENT.send(method_id, *arguments, &block).collect |item| 

显然,它有一个方法“收集”这些论据欺骗了我,认为它是Enumerable ...去图。

2

您提供的代码适用于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) 
+0

我刚刚通过jruby 1.5.3(通过rvm安装)进行了测试,并且它也可以工作。 – 2010-11-04 03:47:15

+0

原来这个问题是由于我对我使用的Java库做了一个假设,很抱歉浪费你的时间。 – Karl 2010-11-04 04:17:20

相关问题