Reputation: 6852
Really I'm not sure whether to ask the user to make sure they are in their home directory before running the commands and abort if not or just change the directory for them?
Dir.chdir
without an argument defaults to the users home directory, and when the block finishes it returns to the previous directory
Dir.chdir do
puts Dir.pwd
end
puts Dir.pwd
# => 'Users/Brian'
# => '/Users/Brian/gems/etc...'
I would need to chdir
quite a few times throughout the code. Is this pretty reliable?
Anybody have any insight on the best way to do this kind of thing?
Upvotes: 0
Views: 78
Reputation: 4796
To summarize Avdi Grimm's screencast on the same subject,
If you're using a Ruby version greater than 1.9, the Dir
module provides a method #home
. However, this depends on the environment variable HOME
set on the user's shell session. To reliably get the home dir, you should pass in the login name of the current user to the Dir.home
command. Or, in code:
# Works if HOME is set in the environment i.e., if "echo $HOME" returns the home directory
# when that command is run on the command-line
Dir.home # => /Users/<username>, Works if HOME is set
# If the HOME environment variable is not set, you should explicitly pass in the username
# of the currently logged-in user
Dir.home(username) # => /Users/<username>
# The current username can be obtained using
username = `whoami`
# or
require 'etc'
username = Etc.getlogin
Now for the final caveat: This works on *nix.
Upvotes: 1