2012-01-17 74 views
2

據我所知,當Ruby正在處理消息時,method_missing是最後的手段。我的理解是,它在對象層次結構中尋找與符號匹配的已聲明方法,然後返回查找聲明最低的method_missing。這比標準的方法調用慢得多。Ruby在method_missing之前的任何方式來捕獲消息?

是否可以在此之前攔截髮送的消息?我嘗試覆蓋send,這在send的調用是明確的時候有效,但是當它是隱式的時候不會。

+0

不這麼認爲 - 的方法是不缺的,如果有一個超類實現。 – 2012-01-17 01:53:40

回答

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! 
+0

我喜歡這個想法 - 謝謝。 – Finbarr 2012-01-17 04:33:13

相關問題