获取调用者类 [英] Get caller class
问题描述
我正在编写 Logger,但在自动添加类名时遇到了问题,我从中调用了 print_log 方法.例如这样的事情:
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 self.print_log(string)
puts Time.now.strftime('%T | ') + *caller_class_name_here* + ' - ' + string
end
end
class MyClass
def initialize
Logger.print_log 'called .new() method'
end
end
作为调用 MyClass.new
方法的结果,我想在输出中看到:
As result of calling MyClass.new
method I wanna see in output:
14:41:23 |MyClass - 调用 .new() 方法
14:41:23 | MyClass - called .new() method
我确信可以使用 caller
,但我还是找不到方法
I'm sure it's possible to do using caller
, but yet can't find how
推荐答案
在与 caller
讨论了一段时间后,它可能不会为你做这件事,caller_locations 也不会代码>.可以跟踪在当前线程上实例化的最后一个对象的类,例如
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
这保留了最后 10 个对象的类,但这并不直接等同于层次结构,例如
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 输出以下内容(在控制台会话中)
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
这篇关于获取调用者类的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!