2011-08-26 62 views
1

標題聽起來很荒謬,因爲它是。我最大的問題在於試圖找出要問什麼問題。Ruby本地範圍的靜態方法

  1. 目標:能夠實現下面描述的代碼或找出我應該用來搜索正確答案的術語。

  2. 問題:我希望有一個系統,其中類通過類定義中的方法註冊「處理器」。例如:

    class RunTheseMethodsWhenICallProcess 
        Include ProcessRunner 
    
        add_processor :a_method_to_run 
        add_processor :another_method_to_run 
    
        def a_method_to_run 
        puts "This method ran" 
        end 
    
        def another_method_to_run 
        puts "another method ran" 
        end 
    
    end 
    
    Module ProcessRunner 
        def process 
        processors.each {|meth| self.send(meth)} 
        end 
    end 
    

我的問題大多與理解類的範圍和參考,使他們互動。就目前而言,我可以通過在所包含的方法中調用class.extend(AClass)並在其中添加一個靜態方法'add_processor'。

這個語法的想法是受DataMapper'property'和'before'方法的啓發。即使代碼被檢出,我也會遇到一些麻煩。

非常感謝您提供的幫助。

+0

HA。當我意識到時,我剛剛打開它來做同樣的事情。我也添加了一個要點,如果有人想用git代替 –

+0

https://gist.github.com/1172736 –

回答

1

如果我找到了你的話,下面會做你想做的。

它初始化每個類(或模塊),包括ProcessRunner@@processors中有一個空數組。另外它增加了類別方法processors(一個簡單的getter)和add_processor。 必須調整process方法以使用類方法。事實上,你可以爲此添加一個包裝,但我認爲這將是對這樣一個樣本冗長。

module ProcessRunner 

    module ClassMethods 
    def add_processor(processor) 
     processors << processor 
    end 

    def processors 
     class_variable_get :@@processors 
    end 
    end 

    def self.included(mod) 
    mod.send :class_variable_set, :@@processors, [] 

    mod.extend ClassMethods 
    end 

    def process 
    self.class.processors.each {|meth| self.send(meth)} 
    end 

end 

class RunTheseMethodsWhenICallProcess 
    include ProcessRunner 

    add_processor :a_method_to_run 
    add_processor :another_method_to_run 

    def a_method_to_run 
    puts "This method ran" 
    end 

    def another_method_to_run 
    puts "another method ran" 
    end 

end