Get caller class

前端 未结 3 1147
小蘑菇
小蘑菇 2021-02-19 09:38

I\'m writing Logger and got problem with automatic adding class name, from which I called print_log method. For example something like this:

class Logger
  def s         


        
3条回答
  •  我在风中等你
    2021-02-19 09:50

    After futzing about with caller for a while, it's probably not going to do it for you, and neither is caller_locations. It's possible to track the classes of the last objects instantiated on the current thread, e.g.

    class Class
      alias :_new :new
      def new *args
        Thread.current.thread_variable_set :classes, ((Thread.current.thread_variable_get(:classes) || []) << self).last(10)
        _new *args
      end
    end
    

    This retains the classes of the last 10 objects, but this isn't directly equivalent to a hierarchy e.g.

    class X
      def initialize
        puts Thread.current.thread_variable_get(:classes)
      end
    end
    
    class Y
    end
    
    class Z
      def initialize
        @y = Y.new
        @x = X.new
      end
    end
    

    X.new outputs the following (in a console session)

    RubyToken::TkNL
    RubyToken::TkEND
    RubyToken::TkNL
    RubyToken::TkCONSTANT
    RubyToken::TkDOT
    RubyToken::TkIDENTIFIER
    RubyToken::TkNL
    Y
    Z
    X
    

提交回复
热议问题