Reading files elsewhere in directory w/ Ruby

path, ruby

Solution

Use relative path:

path = File.join(
    File.dirname(File.dirname(File.absolute_path(__FILE__))),
    'info.config'
)
JSON.parse(File.read(path))

- `File.dirname(File.absolute_path(__FILE__))` will give you the directory where `test.rb` resides. -> (1)

- `File.dirname(File.dirname(File.absolute_path(__FILE__)))` will give you parent directory of (1).

Reference: `File::absolute_path`, `File::dirname`

UPDATE

Using `File::expand_path` is more readable.

path = File.expand_path('../../info.config', __FILE__)
JSON.parse(File.read(path))

Problem

I've got a project structure as follows: - info.config (just a JSON file w/ prefs+creds) - main.rb - tasks/ - test.rb In both main.rb (at the root of the project), and test.rb (under the tasks folder), I want to be able to read and parse the info.config file. I've figured out how to do that in main.rb with the following: ``` JSON.parse(File.read('info.config')) ``` Of course, that doesn't work in test.rb. Question: How can I read the file from a test.rb even though it's one level deeper in the hierarchy? Appreciate any guidance I can get! Thanks!

Original source