Accessing the real file name of a symbolic linked file

风格不统一 提交于 2019-12-23 19:22:20

问题


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?


回答1:


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"]


来源:https://stackoverflow.com/questions/18935615/accessing-the-real-file-name-of-a-symbolic-linked-file

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!