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

Fin*_*arr 2 ruby metaprogramming

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

是否有可能在此之前拦截已发送的消息?我尝试重写send,当调用send是显式的时,这是有效的,但是当它是隐式调用时则不行.

Ale*_*yne 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!'
Run Code Online (Sandbox Code Playgroud)

运行时会吐出这个:

Defining method named: echo_string
you passed in: wtf
you passed in: hello
you passed in: yay!
Run Code Online (Sandbox Code Playgroud)