How do I wrap the invocation of a Ruby method by including a module?

前端 未结 3 1228
暖寄归人
暖寄归人 2020-12-29 13:52

I want to be notified when certain things happen in some of my classes. I want to set this up in such a way that the implementation of my methods in those classes doesn\'t c

3条回答
  •  执笔经年
    2020-12-29 14:23

    I imagine you could use an alias method chain.

    Something like this:

    def notify_when(method)  
      alias_method "#{method}_without_notification", method
      define_method method do |*args|
        puts "#{method} called"
        send "#{method}_without_notification", args
      end
    end
    

    You do not have to modify methods yourself with this approach.

提交回复
热议问题