访问符号链接文件的真实文件名 [英] Accessing the real file name of a symbolic linked file

查看:71
本文介绍了访问符号链接文件的真实文件名的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

通过符号链接加载/要求文件时,所有引用文件名的方法,关键字等似乎都引用了链接名,而不是实际文件名.例如,假设我有一个文件foo.rb,其内容类似于:

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

和指向foo.rb的符号链接bar.rb.如果我通过符号链接bar.rb加载/要求foo.rb,则上述命令给定的所有文件名都描述了符号链接名bar.rb,而不是真实文件名foo.rb.

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.

是否可以使用文件名指向实际文件而不是符号链接名来调用__FILE____dir__caller等的对应项?

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?

推荐答案

您无法如此轻松地更改所有这些常量和内置函数,但是您可以执行以下操作:

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

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

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

示例文件 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

输出:

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

这篇关于访问符号链接文件的真实文件名的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆