__FILE__
返回当前Ruby脚本文件的路径。
一个潜在的重大问题是,如果使用binding.pry
,则__FILE__
的值为(pry)
。根据是否在__FILE__
上下文中进行评估,使binding.pry
评估为不同的值可能存在问题。例如,
$stdout.print "****************************************\n\n"
$stdout.print "FILE: #{__FILE__}\n\n"
$stdout.print "****************************************\n\n"
binding.pry
当脚本在binding.pry
处暂停时,我得到:
__FILE__
# >> (pry)
即使在binding.pry
的情况下,有人知道任何机制来获取当前文件的路径吗?
答案 0 :(得分:2)
使用_file_
代替__FILE__
。例如,给定两个文件:
# foo.rb
require 'pry'
require './bar'
binding.pry
b = Bar.new
和:
# bar.rb
require 'pry'
class Bar
def initialize
binding.pry
end
end
使用ruby foo.rb
运行它们:
ruby foo.rb
From: /Users/username/foo.rb @ line 3 :
1: require 'pry'
2: require './bar'
=> 3: binding.pry
4: b = Bar.new
(main):1 ⇒ _file_
=> "/Users/username/foo.rb"
(main):2 ⇒ exit
From: /Users/username/bar.rb @ line 4 Bar#initialize:
3: def initialize
=> 4: binding.pry
5: end
(#<Bar:0x00007fbb6caaff08>):1 ⇒ _file_
=> "/Users/username/bar.rb"
_file_
和其他任何局部变量名称都可以在binding.local_variables
中找到。
答案 1 :(得分:1)
Sergio Tulentsev提出了一个简单的建议,在调用__FILE__
之前将binding.pry
分配给变量。
另一条提到的_file_
,可用于捆绑撬动。
最后,我结合了两个答案:
# When in the context of binding.pry, __FILE__ resolves to '(pry)',
# binding contains the local variable _file_ which always resolves to
# the current file, even when being evaluated in the context of binding.pry .
# _file_ is only available, in binding. This does the trick:
current_file = __FILE__.downcase == '(pry)' ? _file_ : __FILE__