2010-12-09 94 views
1

HI紅寶石動態鏈接方法

我嘗試建立一些動態定義的方法和鏈條一些範圍的方法是這樣的:

define_method "#{instance_name_method}" do 
     Kernel.const_get(model_name).___some_chaining methods basd on condition 
end 

一個想法是這樣的:

method_action = model_name #ex Post 

['latest', 'old', 'deleted','latest_deleted','archived'].each do |prefix| 

    method_action << ".deleted" if prefix.match('deleted') 
    method_action << ".latest" if prefix.match('latest') 
    method_action << ".old" if prefix.match('old') 

    define_method "#{prefix}_#{instance_name_method}" do 
      eval(method_action) 
    end 


end 

在後我們defiend示波器最新,舊...

現在我們可以調用像這樣的方法:

Post.latest or Post.old_archived etc... 

我的問題是:

  1. 是否有這樣做的更好的辦法? (類似於活動記錄查找,但沒有method_missing)這是好得難看的...

  2. 如何動態鏈接方法?

我已經知道發送(「方法」,VAR),但我不知道如何加入基於狀態的字符串這些方法...

感謝

回答

0

我抱歉,但我很難理解你在問什麼。我不確定你是否正確使用了一些術語,例如「範圍方法」是什麼意思?你是指類方法與實例方法?這將涉及範圍。

而當你說鏈條的時候,你的意思是一個接一個地調用另一個方法嗎?像這樣?

f = Foo.new 
puts f.method1(some_value).method2(some_other_value) 

我只評論說,你不是那麼有活力的部分上面可以寫爲:

method_action << ".#{prefix}" 

我沒有看到任何實際的鏈接在你的問題,所以我不知道你是否僅僅意味着連接刺激以動態構建名稱。如果你確實想要鏈接方法,那麼你需要記住,你需要總是在你想要鏈接的方法結束時返回自己。

例如:

class Foo 

    def method1(value) 
    puts "method1 called with #{value}" 
    self 
    end 

    def method2(value) 
    puts "method2 called with #{value}" 
    self 
    end 

end 

f = Foo.new 
puts f.method1("Hello").method2("World").method1("I can").method2("do this").method2("all").method1("day!") 

將輸出:

method1 called with Hello 
method2 called with World 
method1 called with I can 
method2 called with do this 
method2 called with all 
method1 called with day! 
#<Foo:0x0000010084de50>