Is there a hook similar to Class#inherited that's triggered only after a Ruby class definition?

前端 未结 8 2135
无人共我
无人共我 2020-12-03 13:35

#inherited is called right after the class Foo statement. I want something that\'ll run only after the end statement that closes the c

8条回答
  •  暖寄归人
    2020-12-03 14:29

    I am late, but I think I have an answer (to anyone who visit here).

    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
    

    Output:

    YYY
    XXX
    

提交回复
热议问题