我写了这个模块:与类如何包括重新定义的方法包括
module Hooks
module ExecutionHooks
def before_action(hook, *method_names)
method_names.each do |method_name|
method = method(method_name)
define_singleton_method(method_name) do |*args, &block|
method(hook).call(*args)
method.call(*args, &block)
end
end
end
end
def self.included(base)
base.send(:extend, Hooks::ExecutionHooks)
end
end
这个模块允许其他模块或类来定义一个钩子应该类似于Rails的一个before_action
特定的动作之前被调用。 然后,我包括在我HTTParty模块该模块:
module HTTParty
include Hooks
before_action :perform_action, :get
def self.perform_action
puts "performed"
end
end
有一类,其中包括了HTTParty模块:
class TestClient
include HTTParty
...
end
当我尝试访问TestClient的的get
方法,它不致电perform_action
。这里包含的get
方法是原始方法,而不是重新定义的方法。
有没有办法在TestClient类中包含重新定义的get
方法?
我认为你的代码看起来非常接近目标,但更现代的方法是在'Module#prepend'中使用'super'。 – sawa
我对Ruby很新。请解释一下,我应该在代码的哪一点使用Module#prepend? – crashstorm
请先阅读'prepend'文档,如果需要进行进一步研究并进行实验,然后再要求我们编写更多文档。 –