Ruby是否提供了constant_added的hook方法? [英] Does Ruby provide a constant_added hook method?
问题描述
我知道Ruby提供了几种有用的钩子方法。但是,我似乎找不到 constant_added
钩子之类的东西。我想要一个的原因是我希望重写它,以便每当添加一个常量时,就可以执行某些其他操作来更新某些变量,而不必自己调用某种更新方法。
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?
推荐答案
我曾经在Ruby 1.9中使用 Kernel.set_trace_func $ c做到了$ c>。您可以继续检查
行
事件。每当发生此类事件时,都可以使用 constants
方法获取上次与常数的差。如果您发现差异,那么就是添加/删除常量的时刻。
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可能具有更强大的API,这允许使用更直接的方法来执行此操作,但我不确定。
Ruby 2.0 may have more powerful API, which allows for a more straightforward way to do it, but I am not sure.
这篇关于Ruby是否提供了constant_added的hook方法?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!