How to create a portable absolute path in Ruby?

Suppose a script needs access to a directory, say /some/where/abc on an "arbitrary" OS. There are several options for creating a 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 that the first solution is quite clear, but idiomatic. In my experience, some code reviews ask for a comment to explain what it does ...

Question

Is there a better way to build an absolute Ruby path where it better means β€œdoes the job and speaks for itself”?

+6
source share
2 answers

What I would understand if I were reviewing the code is that on Windows /tmp not necessarily the best place to create a temporary directory, as well as the original argument '', it may not be obvious for a casual consideration 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 break down the problem into a more general solution that is not related to using tmpdir() , I don't see the round path using the initial idiom (hack?). On Linux, this is not a big deal, maybe, but on Windows with a few drive letters it will. In addition, there is no Ruby or gem API to iterate mount points.

Therefore, my recommendation was to delegate the mount point definition to a configuration parameter, which could be '/' for Linux, 'z:/' for Windows, and smb://domain; user@my.file.server.com /mountpoint smb://domain; user@my.file.server.com /mountpoint for the Samba share, then use File.join(ProjectConfig::MOUNT_POINT, 'some', 'where', 'abc') .

+3
source

File#join is the canonical way to create a portable path in Ruby. I wonder who does the review. Perhaps Ruby is new to your organization.

I agree with @ChrisHeald that accessing documentation is the best way to explain reviewer code.

+2
source

Source: https://habr.com/ru/post/954467/


All Articles