[英]Get current file path in Ruby
How can method detect current file name where it is called (not defined)?方法如何检测调用它的当前文件名(未定义)?
__FILE__
is not working in this case. __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
You can refer to the caller_locations module from ruby kernel Returns the current execution stack---an array containing backtrace location objects.可以参考ruby中的caller_locations模块 kernel 返回当前执行栈---一个包含回溯位置对象的数组。
module Foo
def current_path
caller_locations.first.label
end
end
You could use caller
你可以使用
caller
# lib/foo.rb
module Foo
def current_path
caller[0].split(":")[0]
end
end
# lib/bar.rb
class Bar
include Foo
end
# lib/test.rb
bar = Bar.new
bar.current_path # => Expected lib/bar.rb
I've done it through included callback我已经通过包含的回调完成了
def included(base)
base.instance_variable_set :@source_location, caller_locations.first.path
end
And then simply use class instance variable.然后简单地使用 class 实例变量。
You can use __FILE__
to get the full path of the current file:您可以使用
__FILE__
获取当前文件的完整路径:
> __FILE__
=> "/Users/dorianmariefr/src/template-ruby/lib/template-ruby.rb"
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.