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

我只是一个虾纸丫 提交于 2019-11-28 19:40:41

问题


in HOME/path_test/ I have:

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:

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

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

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

Solution (load_Test.rb):

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

回答1:


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:

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


来源:https://stackoverflow.com/questions/8878389/ruby-loading-config-yaml-file-in-same-dir-as-source

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!