Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Relative path to your project directory

Tags:

ruby

In my Ruby project I am using a mess of things like moving and editing files on several remote boxes and I really need something like a relative path to my root project directory. I have many processing folders which are used in many methods.

Right now I have paths hardcoded, but that makes me unhappy.

like image 384
qwebek Avatar asked Feb 23 '12 15:02

qwebek


People also ask

What is a relative directory path?

A relative path is a way to specify the location of a directory relative to another directory. For example, suppose your documents are in C:\Sample\Documents and your index is in C:\Sample\Index. The absolute path for the documents would be C:\Sample\Documents.

How do I find the relative path of a folder?

var relativePath = Path. GetRelativePath( @"C:\Program Files\Dummy Folder\MyProgram", @"C:\Program Files\Dummy Folder\MyProgram\Data\datafile1. dat"); In the above example, the relativePath variable is equal to Data\datafile1.

What is a relative path relative to?

A relative path refers to a location that is relative to a current directory. Relative paths make use of two special symbols, a dot (.) and a double-dot (..), which translate into the current directory and the parent directory. Double dots are used for moving up in the hierarchy.


1 Answers

You can get current directory (directory of current file) with this

File.dirname(__FILE__) 

You can then join it with relative path to the root

File.join(File.dirname(__FILE__), '../../') # add proper number of .. 

Or you can use expand_path to convert relative path to absolute.

ENV['BUNDLE_GEMFILE'] = File.expand_path('../../Gemfile', File.dirname(__FILE__)) 

Or you can calculate relative path between two dirs.

require 'pathname';  puts Pathname.new('/').relative_path_from(Pathname.new('/some/child/dir/')).to_s # => ../../.. 
like image 196
Sergio Tulentsev Avatar answered Sep 20 '22 17:09

Sergio Tulentsev