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 APII 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"?
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.
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.
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.
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')
.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With