Reputation: 1869
Suppose a Ruby project with the following structure...
project/
|-- data
| `-- data.yaml
|-- lib
| |-- project
| | `-- myclass.rb
| `-- project.rb
Within lib/project/myclass.rb, I load data/data.yaml as shown in the example below...
def MyClass
data = YAML::load(File.open('../../data/data.yaml'))
# Other stuff..
end
Within lib/project.rb, I include project/myclass.rb
If project.rb is run, the following error will be thrown...
Errno::ENOENT: No such file or directory - ../../data/data.yaml
In order to get around this, I have to update the file path used in myclass.rb so that it is relative to the root or the lib directory...
../data/data.yaml
Is there a better way to handle this?
Upvotes: 1
Views: 97
Reputation: 87406
You can load the data like this:
filename = File.join File.dirname(__FILE__), '..', '..', 'data', 'data.yaml'
data = YAML::load File.open filename
The way you are currently doing it is kind of bad because it imposes requirements on the user's current directory when he runs your code.
Alternatively, you can embed the YAML data at the end of your ruby file using the __END__
keyword.
Upvotes: 1