如何在 ruby 中继承回调,在子类定义之后而不是之前触发
class A
def self.inherited(child)
puts "XXX"
end
end
class B < A
puts "YYY"
end
打印出来
XXX
YYY
我希望
YYY
XXX
如果我能以某种方式得到它。
Possible Duplicate:
ruby: can I have something like Class#inherited that's triggered only after the class definition?
class A
def self.inherited(child)
puts "XXX"
end
end
class B < A
puts "YYY"
end
prints out
XXX
YYY
I'd prefer
YYY
XXX
if I could get it somehow.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
您可以跟踪直到找到类定义的结尾。我用一个名为
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
:Output:
这是不可能的。考虑一下:在 Ruby 中,什么时候应该将类定义视为“完成”?
我个人会创建一个名为
finalize!
的类方法,并将类后创建例程放入其中,而不是self.inherited
。您可能可以通过创建一个包装函数来代替:
...或者确实考虑到在某些情况下可能不需要最终确定步骤。
This is not possible. Consider this: when should a class definition be considered "done" in Ruby?
Instead of
self.inherited
, I would personally make a class method calledfinalize!
and put your post-class-creation routine in there.You can probably get away with making a wrapper function instead:
...Or do consider that there may be ways where that finalizing step may not be needed.
AFAIK 没有这样的钩子。
解决方法可能是:
它看起来有点乱,但它的输出是:
这样你就可以保证 B 中的代码在 A 的 after_interited() 之前执行。所以它会执行你想要的操作,但不是按照你想要的方式执行。
There is no such hook AFAIK.
A workaround could be:
It looks a bit messy but its output is:
This way you guarantee that your code in B gets executed before the after_interited() of A. So it does what you want but not the way you want to it.