Ruby在与源相同的目录中加载配置(yaml)文件 [英] Ruby loading config (yaml) file in same dir as source

查看:119
本文介绍了Ruby在与源相同的目录中加载配置(yaml)文件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在HOME/path_test/中,我有:

in HOME/path_test/ I have:

load_test.rb:

load_test.rb:

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

config.yml:

config.yml:

Hello: world!!!

在HOME/path_test/中,我得到了预期的结果:

when in HOME/path_test/ I get as expected:

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

在HOME/(cd ..)中,我得到

when in HOME/ (cd ..) I get

-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 :)

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

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

解决方案(load_Test.rb):

Solution (load_Test.rb):

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

推荐答案

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

You should get path of the current file by:

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

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

Since Ruby 2.0 you can simplify that and use:

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

这篇关于Ruby在与源相同的目录中加载配置(yaml)文件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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