__FILE__
returns the path of the current Ruby script file.
One potentially significant problem is that, if using binding.pry
, __FILE__
evaluates to (pry)
. It is potentially problematic to have __FILE__
evaluate to different values depending on whether it is evaluated in the context of binding.pry
. For example,
$stdout.print "****************************************\n\n"
$stdout.print "FILE: #{__FILE__}\n\n"
$stdout.print "****************************************\n\n"
binding.pry
When the script pauses at binding.pry
, I get:
__FILE__
# >> (pry)
Does anyone know any mechanism to get the path of the current file even in the context of binding.pry
?
Use _file_
instead of __FILE__
. For example, given two files:
# foo.rb
require 'pry'
require './bar'
binding.pry
b = Bar.new
and:
# bar.rb
require 'pry'
class Bar
def initialize
binding.pry
end
end
Run them with 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_
and any other local variable names can be found in binding.local_variables
.