ruby 项目目录的相对路径
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/9416578/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Relative path to your project directory
提问by qwebek
In my Ruby project I am using a mess of things like moving and editing files on several remote boxes and I really need something like a relative path to my root project directory. I have many processing folders which are used in many methods.
在我的 Ruby 项目中,我使用了一堆乱七八糟的东西,比如在几个远程机器上移动和编辑文件,我真的需要像我的根项目目录的相对路径之类的东西。我有许多处理文件夹,用于许多方法。
Right now I have paths hardcoded, but that makes me unhappy.
现在我有硬编码的路径,但这让我不高兴。
回答by Sergio Tulentsev
You can get current directory (directory of current file) with this
您可以使用此获取当前目录(当前文件的目录)
File.dirname(__FILE__)
You can then join it with relative path to the root
然后,您可以将它与根的相对路径连接起来
File.join(File.dirname(__FILE__), '../../') # add proper number of ..
Or you can use expand_pathto convert relative path to absolute.
或者您可以使用expand_path将相对路径转换为绝对路径。
ENV['BUNDLE_GEMFILE'] = File.expand_path('../../Gemfile', File.dirname(__FILE__))
Or you can calculaterelative path between two dirs.
或者您可以计算两个目录之间的相对路径。
require 'pathname';
puts Pathname.new('/').relative_path_from(Pathname.new('/some/child/dir/')).to_s
# => ../../..
回答by Andreas Rayo Kniep
__dir__
Since Ruby 2, you can simply use Kernel-function :__dir__to get the absolute directory-path of the current file. So, to give an example, you could set a constant ROOT_DIR at the start of your project in the (config.rb, environments.rb, constants.rb, or whatever you call it).
从 Ruby 2 开始,您可以简单地使用 Kernel-function:__dir__来获取当前文件的绝对目录路径。因此,举个例子,您可以在项目开始时在(config.rb、environments.rb、constants.rb 或任何您称之为)的文件中设置一个常量 ROOT_DIR。
请参阅Ruby 文档

