【问题标题】:Multiple arguments for method_missingmethod_missing 的多个参数
【发布时间】:2010-11-04 02:28:51
【问题描述】:

我在模型中实现了以下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 类有问题。

【问题讨论】:

  • 感谢您的编辑 - 我想说,这不是全部。我测试了你上面给出的代码,它工作正常。带有 method_missing 的文件中的实际第 50 行会显示很多内容。

标签: ruby-on-rails jruby method-missing


【解决方案1】:

您提供的代码在 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)

【讨论】:

  • 我刚刚用 jruby 1.5.3(通过 rvm 安装)进行了测试,效果也很好。
  • 原来问题是由于我对我使用的 Java 库做出的假设,很抱歉浪费您的时间。
【解决方案2】:

原来问题出在我上面省略的部分:

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

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2012-03-27
    • 1970-01-01
    • 1970-01-01
    • 2012-11-27
    • 1970-01-01
    • 2011-04-04
    • 2017-04-18
    • 1970-01-01
    相关资源
    最近更新 更多