Ruby: How to get the correct full path of a source file after a chdir?

2k views Asked by At

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.pwd before I change the directory).
1

There are 1 answers

0
Aleksei Matiushkin On BEST ANSWER

__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.