问题描述
在我的 Ruby 项目中,我使用了很多东西,比如在几个远程机器上移动和编辑文件,我真的需要一些东西,比如我的根项目目录的相对路径.我有很多处理文件夹,用于多种方法.
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.
现在我对路径进行了硬编码,但这让我很不高兴.
Right now I have paths hardcoded, but that makes me unhappy.
推荐答案
你可以通过这个获取当前目录(当前文件的目录)
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 ..
或者您可以使用expand_path
将相对路径转换为绝对路径.
Or you can use expand_path
to convert relative path to absolute.
ENV['BUNDLE_GEMFILE'] = File.expand_path('../../Gemfile', File.dirname(__FILE__))
或者您可以计算两个目录之间的相对路径.
Or you can calculate relative path between two dirs.
require 'pathname';
puts Pathname.new('/').relative_path_from(Pathname.new('/some/child/dir/')).to_s
# => ../../..
这篇关于项目目录的相对路径的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!