Relative path to your project directory

Ruby

Ruby Problem Overview


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.

Ruby Solutions


Solution 1 - Ruby

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

Solution 2 - Ruby

__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

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionqwebekView Question on Stackoverflow
Solution 1 - RubySergio TulentsevView Answer on Stackoverflow
Solution 2 - RubyAndreas Rayo KniepView Answer on Stackoverflow