qwebek
qwebek

Reputation: 968

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.

Upvotes: 66

Views: 80869

Answers (3)

Sergio Tulentsev
Sergio Tulentsev

Reputation: 230551

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

Upvotes: 142

Daniel Garmoshka
Daniel Garmoshka

Reputation: 6362

ROOT_DIR = File.expand_path(".")
  • you can call it from any sub-script, it will resolve to project root dir

Upvotes: 1

Andreas Rayo Kniep
Andreas Rayo Kniep

Reputation: 6562

__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

Upvotes: 33

Related Questions