2011-08-26 43 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