Does Ruby provide a constant_added hook method?

前端 未结 2 766
情歌与酒
情歌与酒 2021-01-22 07:15

I know that there are several useful hook methods that Ruby provides. However, I couldn\'t seem to find anything like a \'constant_added\' hook. The reason I would

2条回答
  •  太阳男子
    2021-01-22 07:43

    I once did it in Ruby 1.9 using Kernel.set_trace_func. You can keep checking for "line" events. Whenever such event occurs, take the difference of the constants from the previous time using the constants method. If you detect a difference, then that is the moment a constant was added/removed.

    Kernel.set_trace_func ->event, _, _, _, _, _{
      case event
      when "line"
        some_routine
      end
    }
    

    Ruby 2.0 may have more powerful API, which allows for a more straightforward way to do it, but I am not sure.

提交回复
热议问题