4

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 Answers 2

10
file = File.join(File.dirname(__FILE__), '..', 'another_dir', 'file.txt') 

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

Sign up to request clarification or add additional context in comments.

4 Comments

this works well for file = ....., but it isn't parsing when I do require File.(.........)
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 Baronosky, is date_extension.rb in C:/Users/Alex and Paula/Documents/Software Projects/RubyCyrusSorterApp/resources?
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)
0

If you're running Ruby 1.9.2 or later, you can use require_relative instead:

require_relative '../somewhere/file.rb' 

This doesn't solve the general problem of referring to files by their relative path, but if all you're doing is requiring the file, it should work.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.