Reputation: 27875
See the following example:
puts __FILE__ #test.rb
puts File.expand_path(__FILE__) #C:/TEMP/test.rb
Dir.chdir('..')
puts __FILE__ #test.rb
puts File.expand_path(__FILE__) #C:/test.rb
After a (global) chdir
the expand_path
returns a wrong result.
How can I get the correct result?
I tried to use the 2nd parameter of File.expand_path
:
puts File.expand_path(__FILE__, 'temp') #C:/TEMP/test.rb
puts File.expand_path(__FILE__, 'c:/temp') #C:/TEMP/test.rb
But to use it, I must know the path of __FILE__
.
The command require_relative
seems to ignore all chdir
-actions. So I have the hope, there is a way to get the 'real' directory of a file.
Remarks:
Dir.pwd
before I change the directory).Upvotes: 2
Views: 2047
Reputation: 121000
__FILE__
builtin is an instance of String
class:
puts __FILE__.class
# ⇒ String
That means you should not expect any voodoo magic from it. It stores the relative path, this file was loaded at.
ruby C:\TEMP\test.rb # ⇒ __FILE__ == 'C:\TEMP\test.rb'
cd C:\TEMP && ruby test.rb # ⇒ __FILE__ == 'test.rb'
In ruby 2.0 was new builtin __dir__
introduced. It looks like what you are looking for, in case 2.0
-only solution is OK with you.
Upvotes: 3