我想在某些课程中发生某些事情时收到通知.我想以这样的方式设置它,使得我在这些类中的方法的实现不会改变.
我以为我会有以下模块:
module Notifications
extend ActiveSupport::Concern
module ClassMethods
def notify_when(method)
puts "the #{method} method was called!"
# additional suitable notification code
# now, run the method indicated by the `method` argument
end
end
end
Run Code Online (Sandbox Code Playgroud)
然后我可以将它混合到我的类中,如下所示:
class Foo
include Notifications
# notify that we're running :bar, then run bar
notify_when :bar
def bar(...) # bar may have any arbitrary signature
# ...
end
end
Run Code Online (Sandbox Code Playgroud)
我的主要愿望是我不想修改:bar以使通知正常工作.可以这样做吗?如果是这样,我将如何编写notify_when实现?
此外,我正在使用Rails 3,所以如果有ActiveSupport或我可以使用的其他技术,请随时分享.(我查看了ActiveSupport :: Notifications,但这需要我修改bar方法.)
我注意到我可能想要使用"模块+超级技巧".我不确定这是什么 - 也许有人可以启发我?