具有本地作用域的 Ruby 静态方法
这个标题听起来很可笑,因为事实确实如此。我最大的问题实际上是试图弄清楚要问什么问题。
目标:能够实现如下所述的代码,或者弄清楚我应该使用什么术语来搜索正确的答案。
问题:我希望有一个系统,其中类通过类定义中的方法注册“处理器”。例如:
类 RunTheseMethodsWhenICallProcess 包括 ProcessRunner 添加处理器:要运行的方法 添加处理器:要运行的另一个方法 def a_method_to_run 提出“这个方法运行” 结尾 def another_method_to_run 提出“另一种方法运行” 结尾 结尾 模块流程运行器 定义过程 处理器.each {|meth| self.send(meth)} 结尾 结尾
我的问题主要是理解类的范围和参考以使它们交互。就目前情况而言,我已经能够通过在包含的方法中调用 class.extend(AClass) 并在其中添加类来添加静态方法“add_processor”。
这种语法的想法受到 DataMappers 的“property”和“before”方法的启发。即使检查了代码,我在遵循它时也遇到了一些麻烦。
非常感谢您提供的任何帮助。
The title sounds rediculous because it is. My biggest issue is actually trying to figure out what question to ask.
The goal: To be able to implement the code as described below OR to figure out what terminology I should be using to search for the correct answer.
The issue: I wish to have a system where classes register "processors" via a method within the class definition. eg:
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
My issues are mostly with understanding the scope and reference of the class to make them interact. As it stands, I have been able to add a static method 'add_processor' by calling class.extend(AClass) in the included method and adding in the class there.
The idea for this syntax was inspired by DataMappers 'property' and 'before' methods. Even with the code checked out, I am having a touch of trouble following it.
Thanks so much for any help you can offer.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
如果我没猜错的话,下面的内容就会满足你的要求。
它初始化每个类(或模块),包括
ProcessRunner
,以便在@@processors
中拥有一个空数组。此外,它还添加了类方法processors
(一个简单的getter)和add_processor
。必须调整
process
方法才能使用类方法。事实上,您可以为此添加一个包装器,但我认为对于这样的示例来说这会过于冗长。If I got you right, the following will do what you want.
It initializes each class (or module) including
ProcessRunner
to have an empty array in@@processors
. Additionally it adds class methodsprocessors
(a simple getter) andadd_processor
.The
process
method had to be adjusted to use the class method. In fact, you could add a wrapper for this, but I think that would be to verbose for such a sample.