是否有一个类似于继承的类的钩子只有在Ruby类定义后触发?

编程入门 行业动态 更新时间:2024-10-24 18:24:53
本文介绍了是否有一个类似于继承的类的钩子只有在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类定义后触发?

本文发布于:2023-11-06 21:21:32,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1564702.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:钩子   类似于   有一个   定义   Ruby

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!