tags:

views:

59

answers:

1
+1  Q: 

File paths in Ruby

So I want to make a file path relative to the directory it is in, in Ruby.

I have a project, and I want it to be able to find the file no matter what directory the project is unzipped into. (Say the code is run on different machines, for example) I can't figure it out for the life of me.

It seems for requires that I can do this:

require File.dirname(__FILE__) + '/comparison'

What can I do for a file that is in a different directory than my src folder?

Instead of listing,

file = 'C:/whole path/long/very_long/file.txt'

I'd like to say:

file = 'file.txt'

or

file = File.helpful_method + 'file.txt'
+2  A: 
file = File.join(File.dirname(__FILE__), '..', 'another_dir', 'file.txt')

Replace '..', 'another_dir' with the relative path segments that reach 'file.txt'.

dan
this works well for file = ....., but it isn't parsing when I do require File.(.........)
Alex Baranosky
require File.join(File.dirname(____FILE____), '..', 'resources', 'date_extension.rb') is giving me the this error: no such file to load -- C:/Users/Alex and Paula/Documents/Software Projects/RubyCyrusSorterApp/specs/../resources/date_extension.rb
Alex Baranosky
@Alex Baronosky, is date_extension.rb in `C:/Users/Alex and Paula/Documents/Software Projects/RubyCyrusSorterApp/resources`?
Wayne Conrad
Try checking for the existence of the file with a line before the `require` but after the `file = File.join...` with this line: `raise('file missing') unless File.exist?(file)`
dan