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.
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.
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.
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.
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 # => ../../..
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With