How to upload files from a specific relative path in Ruby?

I make a gem for domestic use. In it, I load some YAML from another directory:

# in <project_root>/bin/magicwand
MagicWand::Configuration::Initializer.new(...)

# in <project_root>/lib/magicwand/configuration/initializer.rb
root_yaml = YAML.load_file(
  File.expand_path("../../../../data/#{RootFileName}", __FILE__))

# in <project_root>/data/root.yaml
---
apple:   100
banana:  200
coconut: 300

I prefer not to depend on location data/root.yamlrelatively initializer.rb. Instead, I would rather get a link to <project_root>and depend on a relative path from there, which seems smarter.

Firstly, is this the best way to do this? Secondly, if so, how do I do this? I have tested various methods File, but I don’t think something like that. I am using Ruby 1.9.

Now I am creating a special constant and rely on it instead:

# in lib/magicwand/magicwand.rb
module MagicWand
  # Project root directory.
  ROOT = File.expand_path("../..", __FILE__)
end

but I'm not sure that I like this approach either.

+5
1

, , . ( ) $0, data/root.yaml (, root.yaml),

path_to_root_yaml = File.dirname($0) + '/data/root.yaml'
+4

All Articles