如何确定Ruby对象的定义位置?
在两个文件中考虑以下代码: 创建_object.rb如何确定Ruby对象的定义位置?,ruby,Ruby,在两个文件中考虑以下代码: 创建_object.rb def create_object method = 'new' Object.send(method) end debug.rb require_relative './create_object' def foo object = create_object bar(object) end def bar(object) # history_of_life - some method that returns o
def create_object
method = 'new'
Object.send(method)
end
debug.rb
require_relative './create_object'
def foo
object = create_object
bar(object)
end
def bar(object)
# history_of_life - some method that returns object info
puts object.history_of_life
end
foo
require 'objspace'
require_relative './create_object'
def foo
object = create_object
bar(object)
end
def bar(object)
puts ObjectSpace.allocation_sourcefile(object)
end
ObjectSpace.trace_object_allocations do
foo
end
运行ruby debug.rb。我希望history\u of_life
方法返回如下内容:
在create_object.rb:3中初始化
是否有类似于pry stacktrace
的工具来确定对象在代码中的初始化位置?由于占用大量空间,它在默认情况下是关闭的,但使用它可以实现或多或少的期望行为
一般来说,ObjectSpace
tweaks是您在顶级()抽象级别执行类似任务的朋友。ObjectSpace.allocation\u sourcefile
返回给定对象的源文件来源。谢谢你的建议
debug.rb
require_relative './create_object'
def foo
object = create_object
bar(object)
end
def bar(object)
# history_of_life - some method that returns object info
puts object.history_of_life
end
foo
require 'objspace'
require_relative './create_object'
def foo
object = create_object
bar(object)
end
def bar(object)
puts ObjectSpace.allocation_sourcefile(object)
end
ObjectSpace.trace_object_allocations do
foo
end
输出
/home/user/pro/test/create_object.rb
另外,未记录的RubyVM::InstructionSequence
可能是一个很好的灵感来源。您可以覆盖创建\u对象
并打印其调用方
。