Ruby以什么方式在method_missing之前捕获消息?

时间:2012-01-17 01:38:20

标签: ruby metaprogramming

我知道当Ruby处理消息时,method_missing是最后的手段。我的理解是它在Object层次结构中寻找与符号匹配的声明方法,然后返回查找最低声明的method_missing。这比标准方法调用要慢得多。

在此之前是否可以拦截已发送的消息?我尝试覆盖send,当send的调用是显式的时,这种方式有效,但是当它是隐含的时,则无效。

1 个答案:

答案 0 :(得分:5)

不是我知道的。

最高性能的赌注通常是使用method_missing动态地将方法添加到被调用的类中,这样开销只会产生一次。从那时起,它就像任何其他方法一样调用方法。

如:

class Foo
  def method_missing(name, str)

    # log something out when we call method_missing so we know it only happens once
    puts "Defining method named: #{name}"

    # Define the new instance method
    self.class.class_eval <<-CODE
      def #{name}(arg1)
        puts 'you passed in: ' + arg1.to_s
      end
    CODE

    # Run the instance method we just created to return the value on this first run
    send name, str
  end
end

# See if it works
f = Foo.new
f.echo_string 'wtf'
f.echo_string 'hello'
f.echo_string 'yay!'

运行时会吐出这个:

Defining method named: echo_string
you passed in: wtf
you passed in: hello
you passed in: yay!