Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Reading files elsewhere in directory w/ Ruby

Tags:

path

ruby

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!

like image 552
avk Avatar asked Dec 12 '22 07:12

avk


1 Answers

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))
like image 189
falsetru Avatar answered Mar 23 '23 23:03

falsetru