在Ruby中获取当前文件路径

推荐

方法如何检测调用它的当前文件名(未定义)?__FILE__在这种情况下不起作用。

# lib/foo.rb
module Foo
  def current_path
    # Somehow get path lib/bar.rb
  end
end

# lib/bar.rb
class Bar
  inculde Foo
end

# lib/test.rb
bar = Bar.new
bar.current_path # => Expected lib/bar.rb
比延德拉

您可以从ruby内核引用caller_locations模块。返回当前执行堆栈-包含回溯位置对象的数组。

module Foo
  def current_path
    caller_locations.first.label
  end
end

本文收集自互联网,转载请注明来源。

如有侵权,请联系 [email protected] 删除。

编辑于
0

我来说两句

0 条评论
登录 后参与评论

相关文章