简体   繁体   中英

Given a path, how to determine if its 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?

require 'pathname'
(Pathname.new "/foo").absolute? # => true
(Pathname.new "foo").absolute? # => false

The method you're looking for is realpath.

Essentially you do this:

absolute_path = Pathname.new(path).realpath

NB: 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.

There is a built-in function that covers both cases and does exactly what you want:

output_path = File.absolute_path(user_supplied_path, FOO_HOME)

The trick is supplying a second argument. It servers as a base directory if (and only if) the first argument is a relative path.

Pathname can do all that for you

require "pathname"
home= Pathname.new("/home/foo")

home + Pathname.new("/bin") # => #<Pathname:/bin>
home + Pathname.new("documents") # => #<Pathname:/home/foo/documents>

I am not sure about this on windows though.

You could also use File.expand_path if the relative directory is relative to the current working directory.

I checked on Linux and windows and didn't have any issues.

Assuming FOO_HOME is the working directory, the code would be:

output_path = File.expand_path user_supplied_relative_path

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM