42

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']
FelixHJ
  • 1,071
  • 3
  • 12
  • 26

1 Answers1

89

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'))
Hauleth
  • 22,873
  • 4
  • 61
  • 112
  • Thanks (one ')' too much at the end :] ) just what I needed – FelixHJ Jan 16 '12 at 10:19
  • 3
    This is the full solution (split on 2 lines for clarity): ` require 'yaml' fn = File.dirname(File.expand_path(__FILE__)) + '/config.yml' cnf = YAML::load(File.open(fn)) puts cnf['Hello']` – FelixHJ Jan 16 '12 at 10:22
  • I had to use YAML::load_file for this to work for me. YAML::load just returned a string representing the results for File.join. – Tom Feb 18 '13 at 23:40
  • 1
    For the 2.0 solution, doesn't this need to be `nf = YAML::load_file(File.join(__dir__, 'config.yml'))` (with lowercase `__dir__`)? – nickcoxdotme Jun 25 '13 at 03:43
  • `__dir__` represents the path of the current file being executed? – macool Dec 18 '13 at 15:11
  • http://stackoverflow.com/questions/15190700/why-is-file-uppercase-and-dir-lowercase - it is method that do the same as `File.dirname(File.expand_path(__FILE__))`. So no, it is directory of *this* file, not executed one. – Hauleth Dec 18 '13 at 15:19
  • 2
    To get path to current file executed then you should use `File.dirname(File.expand_path($0))`. – Hauleth Sep 22 '14 at 12:59
  • It's preferable in ruby to call class methods with `.` and not `::`, so `YAML.load_file` would be better. – Lev Lukomsky Jan 21 '19 at 22:53