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

FelixHJ picture FelixHJ · Jan 16, 2012 · Viewed 53.8k times · Source

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']

Answer

Hauleth picture Hauleth · Jan 16, 2012

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