Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 870
Daniel Brady Avatar asked Oct 27 '25 13:10

Daniel Brady


2 Answers

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.

like image 160
sawa Avatar answered Oct 30 '25 07:10

sawa


Module#const_added is coming in Ruby 3.2. Looks like this:

Foo::BAR = 42 # call Foo.const_added(:BAR)
class Foo::Baz; end # call Foo.const_added(:Baz)
Foo.autoload(:Something, "path") # call Foo.const_added(:Something)
like image 29
Chris Salzberg Avatar answered Oct 30 '25 05:10

Chris Salzberg



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!