为 Ruby 模块中的每个方法调用执行代码
我正在 Ruby 1.9.2 中编写一个定义了多种方法的模块。当调用这些方法中的任何一个时,我希望它们中的每个方法首先执行某个语句。
module MyModule
def go_forth
a re-used statement
# code particular to this method follows ...
end
def and_multiply
a re-used statement
# then something completely different ...
end
end
但我想避免在每个方法中显式放置重用语句
代码。有办法这样做吗?
(如果重要的话,重用语句
将使每个方法在调用时打印自己的名称。它将通过puts __method__
的某种变体来实现。)
I'm writing a module in Ruby 1.9.2 that defines several methods. When any of these methods is called, I want each of them to execute a certain statement first.
module MyModule
def go_forth
a re-used statement
# code particular to this method follows ...
end
def and_multiply
a re-used statement
# then something completely different ...
end
end
But I want to avoid putting that a re-used statement
code explicitly in every single method. Is there a way to do so?
(If it matters, a re-used statement
will have each method, when called, print its own name. It will do so via some variant of puts __method__
.)
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(6)
像这样:
Like this:
这正是创建 spector 的目的。
使用aspector,您不需要编写样板元编程代码。您甚至可以更进一步,将通用逻辑提取到一个单独的方面类中并对其进行独立测试。
This is exactly what aspector is created for.
With aspector you don't need to write the boilerplate metaprogramming code. You can even go one step further to extract the common logic into a separate aspect class and test it independently.
您可以通过代理模块使用
method_missing
来实现它,如下所示:You can implement it with
method_missing
through proxy Module, like this:您可以通过元编程技术来做到这一点,这里有一个示例:
仅适用于 ruby 1.9 及更高版本
更新:并且也不能使用块,即实例方法中没有收益
You can do this by metaprogramming technique, here's an example:
works only in ruby 1.9 and higher
UPDATE: and also can't use block, i.e. no yield in instance methods
我不知道为什么我被否决了——但是一个合适的 AOP 框架比元编程黑客更好。这就是 OP 想要实现的目标。
http://debasishg.blogspot.com/2006/06/does -ruby-need-aop.html
另一种解决方案可能是:
I dunno, why I was downvoted - but a proper AOP framework is better than meta-programming hackery. And thats what OP was trying to achieve.
http://debasishg.blogspot.com/2006/06/does-ruby-need-aop.html
Another Solution could be:
通过元编程是可能的。
另一种选择是水族馆。 Aquarium 是一个为 Ruby 实现面向方面编程 (AOP) 的框架。 AOP 允许您跨普通对象和方法边界实现功能。您的用例,对每个方法应用预操作,是 AOP 的基本任务。
It is possible with meta-programming.
Another alternative is Aquarium. Aquarium is a framework that implements Aspect-Oriented Programming (AOP) for Ruby. AOP allow you to implement functionality across normal object and method boundaries. Your use case, applying a pre-action on every method, is a basic task of AOP.