如何在运行时访问Ruby类的源文件位置



我想访问这样一个类的源代码:

# Module inside file1.rb
module MetaFoo
  class << Object
    def bar
      # here I'd like to access the source location of the Foo class definition
      # which should result in /path/to/file2.rb
    end
  end
end
# Class inside another file2.rb
class Foo
  bar
end

我可以做一些不好的事情,比如:

self.send(:caller)

并尝试解析输出,甚至:

class Foo
  bar __FILE__
end

但这不是,我想要,我曾希望有一个更优雅的解决方案。

欢迎任何提示。

$0__FILE__对您都很有用。

$0是正在运行的应用程序的路径。

__FILE__是当前脚本的路径。

因此,__FILE__将是脚本或模块,即使它是required

此外,__LINE__可能对您有用。

请参阅"__FILE__在Ruby中的意思是什么?"、"if __FILE__ == $0在Ruby中是什么意思"one_answers"class_eval <<-“end_eval”, __FILE__, __LINE__在Ruby中意味着什么?"以了解更多信息。

您可以尝试调用:

caller.first

这将打印出文件名和行号。使用上面的演示文件(稍作修改:

文件1.rb:

module MetaFoo
  class << Object
    def bar
      puts caller.first # <== the magic...
    end
  end
end

文件2.rb:

require './file1.rb'
class Foo
  bar
end

当我运行ruby file2.rb时,我得到以下输出:

nat$ ruby file2.rb 
file2.rb:4:in `<class:Foo>'

这就是你想要的,对吧?

最新更新