为Ruby模块中的每个方法调用执行代码 [英] Executing code for every method call in a Ruby module
本文介绍了为Ruby模块中的每个方法调用执行代码的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我正在用Ruby 1.9.2编写一个模块,该模块定义了几种方法.当这些方法中的任何一个被调用时,我希望它们中的每个都首先执行特定的语句.
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
但是我想避免将a re-used statement
代码明确地放在每个方法中.有办法吗?
But I want to avoid putting that a re-used statement
code explicitly in every single method. Is there a way to do so?
(如果重要的话,a re-used statement
将具有每个方法,当被调用时,将打印其自己的名称.它将通过puts __method__
的某些变体来实现.)
(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__
.)
推荐答案
像这样:
module M
def self.before(*names)
names.each do |name|
m = instance_method(name)
define_method(name) do |*args, &block|
yield
m.bind(self).(*args, &block)
end
end
end
end
module M
def hello
puts "yo"
end
def bye
puts "bum"
end
before(*instance_methods) { puts "start" }
end
class C
include M
end
C.new.bye #=> "start" "bum"
C.new.hello #=> "start" "yo"
这篇关于为Ruby模块中的每个方法调用执行代码的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文