我正在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
Run Code Online (Sandbox Code Playgroud)
但我想避免a re-used statement在每个方法中明确地放置该代码.有办法吗?
(如果重要的话,a re-used statement每个方法在调用时都会打印自己的名字.它会通过一些变体来实现puts __method__.)
这是我的实现,以开发方式在模型中的所有方法之前运行代码
调用"before_hook:months_used"方法需要在类的底部到ExecutionHooks才能获得在模块中加载的instance_method.我想在顶部加载实例方法
class BalanceChart < BalanceFind
include ExecutionHooks
attr_reader :options
def initialize(options = {})
@options = options
@begin_at = @options[:begin_at]
end
def months_used
range.map{|date| I18n.l date, format: :month_year}.uniq!
end
before_hook :months_used
end
module ExecutionHooks
def self.included(base)
base.send :extend, ClassMethods
end
module ClassMethods
def before
@hooks.each do |name|
m = instance_method(name)
define_method(name) do |*args, &block|
return if @begin_at.blank? ## the code you can execute before methods
m.bind(self).(*args, &block) ## your old code in the method of the class
end
end
end …Run Code Online (Sandbox Code Playgroud)