Relative path to your project directory

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.


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
# => ../../..

__dir__

Since Ruby 2, you can simply use Kernel-function :__dir__ to get the absolute directory-path of the current file. So, to give an example, you could set a constant ROOT_DIR at the start of your project in the (config.rb, environments.rb, constants.rb, or whatever you call it).

See Ruby Documentation