sawa
sawa

Reputation: 168199

Accessing the real file name of a symbolic linked file

When a file is loaded/required via a symbolic link, all the methods, keywords, etc. that refer to a file name seem to refer to the link name, and not the real file name. For example, suppose I have a file foo.rb with its contents something like:

puts __FILE__, __dir__, caller

and a symbolic link bar.rb pointing to foo.rb. If I load/require foo.rb via the symbolic link bar.rb, then all of the file names given by the commands above describe the symbolic link name bar.rb, and not the real file name foo.rb.

Is there a way to call the counterparts of __FILE__, __dir__, caller, etc. with the file names pointing to the real file and not the symbolic link names?

Upvotes: 3

Views: 618

Answers (1)

Neil Slater
Neil Slater

Reputation: 27207

You could not change all those constants and built-ins so easily, but you can do this:

File.realpath( "/path/to/file/or/symlink" )

or

require 'pathname'
Pathname.new( "/path/to/file/or/symlink" ).realpath

Example file realfile.rb

names = [ __FILE__, __dir__]
p names
p names.map { |name| File.realpath(name) }

Set up and called like this:

ln -s realfile.rb thelinkfile
ruby thelinkfile

Output:

["thelinkfile", "/Users/neilslater/scraps"]
["/Users/neilslater/scraps/realfile.rb", "/Users/neilslater/scraps"]

Upvotes: 5

Related Questions