本文介绍了是否有一个类似于继承的类的钩子只有在Ruby类定义后触发?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
#inherited
我想要的东西,只有在 end
语句关闭类声明后才会运行。
#inherited
is called right after the class Foo
statement. I want something that'll run only after the end
statement that closes the class declaration.
例如我需要:
class Class
def inherited m
puts "In #inherited for #{m}"
end
end
class Foo
puts "In Foo"
end
puts "I really wanted to have #inherited tiggered here."
### Output:
# In #inherited for Foo
# In Foo
# I really wanted to have #inherited tiggered here.
有没有类似的东西?可以创建吗?
Does anything like that exist? Can it be created? Am I totally out of luck?
推荐答案
我迟到了,但我想我有一个答案(任何人访问这里) 。
I am late, but I think I have an answer (to anyone who visit here).
您可以跟踪,直到找到类定义的结尾。我在一个方法中调用了 after_inherited
:
You can trace until you find the end of the class definition. I did it in a method which I called after_inherited
:
class Class
def after_inherited child = nil, &blk
line_class = nil
set_trace_func(lambda do |event, file, line, id, binding, classname|
unless line_class
# save the line of the inherited class entry
line_class = line if event == 'class'
else
# check the end of inherited class
if line == line_class && event == 'end'
# if so, turn off the trace and call the block
set_trace_func nil
blk.call child
end
end
end)
end
end
# testing...
class A
def self.inherited(child)
after_inherited do
puts "XXX"
end
end
end
class B < A
puts "YYY"
# .... code here can include class << self, etc.
end
输出:
YYY
XXX
这篇关于是否有一个类似于继承的类的钩子只有在Ruby类定义后触发?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!