Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to build a portable absolute path in Ruby?

Tags:

ruby

Let's assume a script needs access a directory, say /some/where/abc on an "arbitrary" OS. There are a couple options to build the path in Ruby:

  • File.join('', 'some', 'where', 'abc')
  • File.absolute_path("some#{File::SEPARATOR}where#{File::SEPARATOR}abc", File::SEPARATOR)
  • Pathname in the standard API

I believe the first solution is clear enough, but idiomatic. In my experience, some code reviews ask for a comment to explain what it does...

The Question

Is there a better way to build an absolute path is Ruby, where better means "does the job and speaks for itself"?

like image 303
Eric Platon Avatar asked Sep 24 '13 01:09

Eric Platon


People also ask

How do you write an absolute path?

A path is either relative or absolute. An absolute path always contains the root element and the complete directory list required to locate the file. For example, /home/sally/statusReport is an absolute path.

How do I put 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.

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.


1 Answers

What I would pick up if I was doing a code review is that on Windows /tmp is not necessarily the best place to create a temporary directory, and also the initial '', argument is perhaps not obvious to the casual reviewed that it creates <nothing>/tmp/abc. Therefore, I would recommend this code:

File.join(Dir.tmpdir(), 'abc')

See Ruby-doc for an explanation.

UPDATE

If we expand the problem to a more generic solution that does not involve using tmpdir(), I cannot see a way round using the initial '' idiom (hack?). On Linux this is not too much of a problem, perhaps, but on Windows with multiple drive letters it will be. Furthermore, there does not appear to be a Ruby API or gem for iterating the mount points.

Therefore, my recommendation would be to delegate the mount point definition to a configuration option that might be '/' for Linux, 'z:/' for Windows, and smb://domain;[email protected]/mountpoint for a Samba share, then use File.join(ProjectConfig::MOUNT_POINT, 'some', 'where', 'abc').

like image 78
Ken Y-N Avatar answered Oct 03 '22 09:10

Ken Y-N