Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Given a path, how to determine if it's absolute/relative in Ruby?

I am working on writing a rake build scrip which will work cross platform ( Mac OSX, Linux , Windows ). The build script will be consumed by a CI server.

I want the logic of my script to be as follows:

  1. If the path is determined to be relative, make it absolute by making output_path = FOO_HOME + user_supplied_relative_path
  2. If the path is determined to be absolute, take it as-is

I'm currently using Pathname.new(location).absolute? but it's not working correctly on windows.

What approach would you suggest for this?

like image 474
Manish Chakravarty Avatar asked Dec 15 '09 11:12

Manish Chakravarty


People also ask

How can you tell if a path is relative or absolute?

In simple words, an absolute path refers to the same location in a file system relative to the root directory, whereas a relative path points to a specific location in a file system relative to the current directory you are working on.

How do you find the absolute path in Ruby?

Pass a string to File. expand_path to generate the path to that file or directory. Relative paths will reference your current working directory, and paths prepended with ~ will use the owner's home directory.

How do you find the relative path in Pokemon Ruby?

If you want to get the path of a file relative to another, you can use the expand_path method with either the constant __FILE__ or the method __dir__ .


2 Answers

require 'pathname'
(Pathname.new "/foo").absolute? # => true
(Pathname.new "foo").absolute? # => false
like image 102
evanmeng Avatar answered Oct 15 '22 10:10

evanmeng


The method you're looking for is realpath.

Essentially you do this:

absolute_path = Pathname.new(path).realpath

N.B.: The Pathname module states that usage is experimental on machines that do not have unix like pathnames. So it's implementation dependent. Looks like JRuby should work on Windows.

like image 38
EmFi Avatar answered Oct 15 '22 10:10

EmFi