2011-06-13 73 views
5

當談到運行時反思和動態代碼生成時,我不認爲ruby除了可能對某些lisp方言有任何競爭對手。有一天,我正在做一些代碼練習來探索ruby的動態設施,我開始想知道如何向現有對象添加方法。這裏有3種方式我能想到的:有多少種方法可以添加到紅寶石對象?

obj = Object.new 

# add a method directly 
def obj.new_method 
    ... 
end 

# add a method indirectly with the singleton class 
class << obj 
    def new_method 
    ... 
    end 
end 

# add a method by opening up the class 
obj.class.class_eval do 
    def new_method 
    ... 
    end 
end 

這是冰山的一角,因爲我還沒有探索的instance_evalmodule_evaldefine_method各種組合。有沒有線上/線下資源,我可以找到更多有關這種動態技巧的資訊?

回答

3

如果obj有一個父類,你可以使用define_method(API)正如你所提到的超添加方法obj。如果你看過Rails源代碼,你會注意到他們這麼做了很多。

此外,雖然這是你的要求不完全是什麼,你可以輕鬆地創建給出的方法幾乎無限多的印象,動態使用method_missing

def method_missing(name, *args) 
    string_name = name.to_s 
    return super unless string_name =~ /^expected_\w+/ 
    # otherwise do something as if you have a method called expected_name 
end 

添加,爲您的類將允許它到任何方法調用它看起來像

@instance.expected_something