Access the real file name of the symbolic linked file

When a file is downloaded / required via a symbolic link, all methods, keywords, etc. that relate to the file name seem to refer to the link name, not the real file name. For example, suppose I have a file foo.rbwith its contents, for example:

puts __FILE__, __dir__, caller

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

Is there a way to call colleagues __FILE__, __dir__, calleretc. with file names pointing to the real file, not symbolic link names?

+3
source share
1 answer

You could not easily change all these constants and built-in modules, but you can do this:

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

or

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

Realfile.rb sample file

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

Set up and call like this:

ln -s realfile.rb thelinkfile
ruby thelinkfile

Output:

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

Source: https://habr.com/ru/post/1620651/


All Articles