Defining “method_called”.. How do I make a hook method which gets called every time any function of a class gets called?

前端 未结 3 1347
北海茫月
北海茫月 2020-12-23 23:43

I want to make a hook method which gets called everytime any function of a class gets called. I have tried method_added, but it executes only once at the time of class defin

3条回答
  •  粉色の甜心
    2020-12-24 00:03

    Take a look at Kernel#set_trace_func. It lets you specify a proc which is invoked whenever an event (such as a method call) occurs. Here's an example:

    class Base
      def a
        puts "in method a"
      end
    
      def b
        puts "in method b"
      end
    end
    
    set_trace_func proc { |event, file, line, id, binding, classname|
      # only interested in events of type 'call' (Ruby method calls)
      # see the docs for set_trace_func for other supported event types
      puts "#{classname} #{id} called" if event == 'call'
    }
    
    b = Base.new
    b.a
    b.b
    

    Outputs:

    Base a called
    in method a
    Base b called
    in method b
    

提交回复
热议问题