如何从 Ruby 中的特定相对路径加载文件? [英] How do I load files from a specific relative path in Ruby?
问题描述
我正在制作一个供内部使用的宝石.在其中,我从另一个目录加载了一些 YAML:
I'm making a gem for internal use. In it, I load some YAML from another directory:
# in <project_root>/bin/magicwand
MagicWand::Configuration::Initializer.new(...)
# in <project_root>/lib/magicwand/configuration/initializer.rb
root_yaml = YAML.load_file(
File.expand_path("../../../../data/#{RootFileName}", __FILE__))
# in <project_root>/data/root.yaml
---
apple: 100
banana: 200
coconut: 300
我宁愿不依赖于 data/root.yaml
相对于 initializer.rb
的位置.相反,我宁愿获得对 <project_root>
的引用并依赖于那里的相对路径,这似乎是一个更明智的举动.
I'd rather not depend on the location of data/root.yaml
relative to initializer.rb
. Instead, I'd rather get a reference to <project_root>
and depend on the relative path from there, which seems like a smarter move.
首先,这是最好的方法吗?其次,如果是这样,我该怎么做?我检查了各种 File
方法,但我认为没有类似的东西.我使用的是 Ruby 1.9.
First, is that the best way to go about this? Second, if so, how do I do that? I checked out the various File
methods, but I don't think there's anything like that. I'm using Ruby 1.9.
现在,我创建了一个特殊的常量并依赖于它:
Right now, I create a special constant and depend on that instead:
# in lib/magicwand/magicwand.rb
module MagicWand
# Project root directory.
ROOT = File.expand_path("../..", __FILE__)
end
但我也不确定我是否喜欢这种方法.
but I'm not sure I like that approach either.
推荐答案
如果有一个您一直在运行的主文件,您可以使用该文件作为参考点.该文件的相对路径(当前目录和)将在 $0
中,因此要获取 data/root.yaml
的相对路径(假设这是相对路径)主文件和 root.yaml
) 之间的路径
If there's a main file you always run you can use that file as a reference point. The relative path (between the current directory and) of that file will be in $0
, so to get the relative path to data/root.yaml
(assuming that is the relative path between the main file and root.yaml
) you do
path_to_root_yaml = File.dirname($0) + '/data/root.yaml'
这篇关于如何从 Ruby 中的特定相对路径加载文件?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!