【问题标题】:How can I access source file location of a Ruby class at runtime?如何在运行时访问 Ruby 类的源文件位置?
【发布时间】:2012-09-12 17:35:14
【问题描述】:

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

# 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

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

欢迎任何提示。

【问题讨论】:

  • 你可以访问方法源的位置,但是要求一个类的位置太模糊了。

标签: ruby-on-rails ruby metaprogramming


【解决方案1】:

$0__FILE__ 都会对你有用。

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

__FILE__ 是当前脚本的路径。

所以,__FILE__ 将是脚本或模块,即使它是 required

另外,__LINE__ 可能对您有用。

有关详细信息,请参阅“What does __FILE__ mean in Ruby?”、“What does if __FILE__ == $0 mean in Ruby”和“What does class_eval &lt;&lt;-“end_eval”, __FILE__, __LINE__ mean in Ruby?”。

【讨论】:

  • 锡人,感谢您的意见。事实上,问题在于 bar 的定义位于模块中,而类 Foo 位于不同的文件中。因此,当从 Foo 中调用 bar 方法时,self 是 Foo,但 FILE 是内部包含 bar 方法定义的模块的位置。 LINE 的行为方式相同,$0 似乎没有提供我当时需要的信息。无论如何,谢谢你的帮助。
【解决方案2】:

您可以尝试调用:

caller.first

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

file1.rb:

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

file2.rb:

require './file1.rb'

class Foo
  bar
end

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

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

这就是你想要的,对吧?

【讨论】:

  • Nat,就是这样,一些 RegEx KungFu 和我有我需要的东西。谢谢。
猜你喜欢
  • 1970-01-01
  • 2016-02-22
  • 1970-01-01
  • 2011-09-23
  • 2014-06-05
  • 2023-04-10
  • 2013-08-15
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多