是否有可能完成这项工作,而不必在课程结束时包含该模块并将其包含在顶部?模块包装类方法?
module VerboseJob
def self.included(job_class)
class << job_class
alias_method :original_perform, :perform
def perform(*args)
JobLogger.verbose { original_perform(*args) }
end
end
end
end
class HelloJob
include VerboseJob
def self.perform(arg1, arg2)
puts "Job invoked with #{arg1} and #{arg2}"
end
end
我希望发生什么,是HelloJob.perform
实际调用VerboseJob.perform
(然后调用块内的原始方法)。因为这里的模块包含在类的顶部,所以这不起作用,因为perform
尚未定义。将include
移到最后确实有效,但有没有更宽容的方法?我喜欢将所有包含的模块保留在我的类定义的顶部。
我正在寻找某种方法,它在完全加载时调用Module
或Class
,而不是像运行时所解释的那样。
为什么不只是使用'method_added'来包装执行'当它是..呃..添加? :) –
我不确定我是否明白你的意思,我不是那样做的吗? –
我把你的答案(结合这个http://pivotallabs.com/users/rolson/blog/articles/1162-redefine-a-method-from-a-module-like-a-gentleman)并提出了更简洁的https://gist.github.com/1170661(它可以在'include'完成的地方工作)。随意编辑你的答案。我会接受它:) – d11wtq