In Ruby/Rake(a gem for Ruby), current file path can be get through Dir.pwd
and __FILE__
.
There are times I want to get the caller's path, like to figure out a relative path the caller provided which is relative to their path (but not relative to the path of the Rakefile).
An example
In a Rakefile from directory /home/me/workspace/proj
:
# ...
task :foo do
file_name = ENV['WHICH_FILE']
# As I can not get the caller dir, give it the Rakefile dir instead
caller_dir = Dir.pwd
file_name = "#{call_dir}/#{file_name}" unless file_name&.match? /^\//
puts File.read file_name
# ...
end
# ...
If a caller provides the absolute path of the target file, no problem:
$ WHICH_FILE=/home/me/workspace/proj/suba/subb/subc/file.txt rake foo
If a caller in /home/me/workspace/proj
provides a relative path, still no problem:
$ WHICH_FILE=suba/subb/subc/file.txt rake foo
If a caller in /home/me/workspace/proj/suba
provides a relative path, the file_name may point to a wrong place:
$ WHICH_FILE=subb/subc/file.txt rake foo
Now file_name
would be /home/me/workspace/proj/subb/subc/file.txt
, which may not be what the caller want.
Questions
Is it possible to get the caller's path in Ruby/Rake? If it's possible, how?
You can tell where the user is right now, like you said, with Dir.pwd
, but there's no way to guess which absolute path the user really wants.
This is why most scripts (or apps, etc) either have a ROOT_DIR
that allows you to default to that as a prefix for the rest of the directory structure or just assume the file passed is under the current folder (shown by pwd).
Your choice is either set this ROOT_DIR somewhere in your code or just being open to the chance the user gives you a relative path to a file without really knowing what the absolute route to that file is and just assume is under their current dir.
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.