代码之家  ›  专栏  ›  技术社区  ›  Karl

缺少方法的多个参数

  •  0
  • Karl  · 技术社区  · 14 年前

    我有以下的 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 是全局对象。注意这是 缺少方法 ,而不是实例。

    我在脚本/控制台中尝试了以下操作:

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

    2 回复  |  直到 12 年前
        1
  •  2
  •   Ben Taitelbaum    14 年前

    你提供的代码在ruby-1.8.7和ruby-1.9.2上都能为我工作,所以听起来你使用的jRuby版本中有个bug。为了完整起见,这是我运行的代码:

    #!/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)
    
        2
  •  0
  •   Karl    14 年前

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

    显然,它定义了一个方法“collect”,其中包含两个参数,这让我误以为它是可枚举的……算了吧。