Son*_*tos 16

您可以跟踪,直到找到类定义的结尾.我用一种方法做到了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
Run Code Online (Sandbox Code Playgroud)

输出:

YYY
XXX
Run Code Online (Sandbox Code Playgroud)

  • 那是可怕的天才:) (2认同)