Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Canonical File Path in Ruby

Tags:

path

ruby

Is there an easy way in Ruby to find a canonical file path out of a messy file path?

For example:

  • a/b/../c/x is the same as a/c/x
  • a/./b/c/x is the same as a/b/c/x
  • a/./b/../../c/x is the same as c/x

Any simple way to do this?

like image 711
Julien Genestoux Avatar asked Aug 17 '10 12:08

Julien Genestoux


People also ask

How do you specify the file path in Ruby?

Ruby has a method for this case. It is File::expand_path . Converts a pathname to an absolute pathname. Relative paths are referenced from the current working directory of the process unless dir_string is given, in which case it will be used as the starting point.

What is canonical path?

The canonical path is always an absolute and unique path. If String pathname is used to create a file object, it simply returns the pathname. This method first converts this pathname to absolute form if needed. To do that it will invoke the getAbsolutePath() Method and then maps it to its unique form.

What is __ file __ Ruby?

In Ruby, the Windows version anyways, I just checked and __FILE__ does not contain the full path to the file. Instead it contains the path to the file relative to where it's being executed from.

What is path in Ruby?

Pathname represents the name of a file or directory on the filesystem, but not the file itself. The pathname depends on the Operating System: Unix, Windows, etc.


2 Answers

require 'pathname'  Pathname.new("a/b/../c/x").cleanpath 
like image 104
Ken Bloom Avatar answered Sep 23 '22 01:09

Ken Bloom


File.expand_path(file_name [, dir_string] ) → abs_file_name

Converts a pathname to an absolute pathname. Relative paths are referenced from the current working directory of the process unless dir_string is given, in which case it will be used as the starting point. The given pathname may start with a ~, which expands to the process owner‘s home directory (the environment variable HOME must be set correctly). ~user expands to the named user‘s home directory.

File.expand_path("~oracle/bin")           #=> "/home/oracle/bin" File.expand_path("../../bin", "/tmp/x")   #=> "/bin" 
like image 39
Matt Briggs Avatar answered Sep 25 '22 01:09

Matt Briggs