Ruby 在与源相同的目录中加载配置 (yaml) 文件

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/8878389/
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

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-06 04:41:13  来源:igfitidea点击:

Ruby loading config (yaml) file in same dir as source

rubypathyamlconfiguration-files

提问by FelixHJ

in HOME/path_test/ I have:

在 HOME/path_test/ 我有:

load_test.rb:

load_test.rb:

require 'yaml'
cnf = YAML::load(File.open('config.yml'))
puts cnf['Hello']

config.yml:

配置文件:

Hello: world!!!

when in HOME/path_test/ I get as expected:

当在 HOME/path_test/ 我得到预期:

-bash-3.2$ ruby load_test.rb 
world!!!

when in HOME/ (cd ..) I get

当在 HOME/ (cd ..) 我得到

-bash-3.2$ ruby path_test/load_test.rb 
path_test/load_test.rb:3:in `initialize': No such file or directory - config.yml     (Errno::ENOENT)
    from path_test/load_test.rb:3:in `open'
    from path_test/load_test.rb:3:in `<main>'

Which is correct behavior, but not what I had wished for :)

这是正确的行为,但不是我所希望的:)

Is there a way to load the .yml file relative to the source file, and not relative to the current working DIR??

有没有办法相对于源文件而不是相对于当前工作目录加载 .yml 文件?

Solution (load_Test.rb):

解决方案(load_Test.rb):

require 'yaml'
fn = File.dirname(File.expand_path(__FILE__)) + '/config.yml'
cnf = YAML::load(File.open(fn))
puts cnf['Hello']

回答by Hauleth

You should get path of the current file by:

您应该通过以下方式获取当前文件的路径:

cnf = YAML::load_file(File.join(File.dirname(File.expand_path(__FILE__)), 'config.yml'))

EDIT:

编辑:

Since Ruby 2.0 you can simplify that and use:

从 Ruby 2.0 开始,您可以简化并使用:

cnf = YAML::load_file(File.join(__dir__, 'config.yml'))