I've got a project structure as follows:
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!
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))
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With