Search code examples
rubyhookconstants

Does Ruby provide a constant_added hook method?


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 like one is because I wish to override it so that whenever a constant is added, certain other actions are performed with regards to updating some variables without having to call some sort of update method myself.

More specifically, I am trying to keep a list of all existing constants that match a particular regex, but without looping over all the existing constants searching for matches at certain intervals or updating the list whenever the last constant added matches the regex; I believe this would require an explicit method call.

If a hook does not already exist, would it be possible to create one, and if not, how might I go about getting this behavior?


Solution

  • 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.