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

前端 未结 8 2132
无人共我
无人共我 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:14

    Use TracePoint to track when your class sends up an :end event.

    This module will let you create a self.finalize callback in any class.

    module Finalize
      def self.extended(obj)
        TracePoint.trace(:end) do |t|
          if obj == t.self
            obj.finalize
            t.disable
          end
        end
      end
    end
    

    Now you can extend your class and define self.finalize, which will run as soon as the class definition ends:

    class Foo
      puts "Top of class"
    
      extend Finalize
    
      def self.finalize
        puts "Finalizing #{self}"
      end
    
      puts "Bottom of class"
    end
    
    puts "Outside class"
    
    # output:
    #   Top of class
    #   Bottom of class
    #   Finalizing Foo
    #   Outside class
    

提交回复
热议问题