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:
- I know the block-version of Dir.chdir - for my specific task i can#t use it.
- My actual solution: I store the fullpath before I change the directory (I could also store
Dir.pwdbefore I change the directory).
__FILE__builtin is an instance ofStringclass:That means you should not expect any voodoo magic from it. It stores the relative path, this file was loaded at.
In ruby 2.0 was new builtin
__dir__introduced. It looks like what you are looking for, in case2.0-only solution is OK with you.