0

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 类中存在问题。

4

2 回答 2

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)
于 2010-11-04T03:41:39.590 回答
0

原来问题实际上是我从上面省略的部分:

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

显然,它定义了一个“收集”方法,它接受了 2 个参数,这让我误以为它是可枚举的……看图。

于 2010-11-04T04:16:34.517 回答