Cross-platform way to get a custom home directory in Ruby?

Java has convienient System.getProperty("user.home") to get the user's home directory in a platform-independent way. What is equivalent in Ruby? I donโ€™t have a Windows window to play with, and I feel that relying on tildes in file names is not the cleanest way. Are there any alternatives?

+48
ruby cross-platform
Nov 16 '10 at 3:19
source share
4 answers

The File.expand_path method uses the Unix convention to process the tilde ( ~ ) specifically, so ~ refers to the user's current home directory and ~foo refers to the foo home directory.

I don't know if there is a better or more idiomatic way, but File.expand_path('~') should catch you.

+73
Nov 16 2018-10-16
source share

With Ruby 1.9 and above, you can use Dir.home .

+81
Sep 25 '11 at 18:05
source share

ENV["HOME"] or ENV["HOMEPATH"] should provide you with what you want.

 homes = ["HOME", "HOMEPATH"] realHome = homes.detect {|h| ENV[h] != nil} if not realHome puts "Could not find home directory" end 
+10
Nov 16 '10 at 3:23
source share

On unix platforms (linux, OS X, etc.), ENV["HOME"] , File.expandpath('~') or Dir.home all rely on the HOME environment variable. But sometimes you find that an environment variable is not set - this is common if you are working with a script run or with some package planners. If you are in this situation, you can get the correct home directory through:

 require 'etc' Etc.getpwuid.dir 

Having said that, since this question requires a cross-platform method, it should be noted that this will not work on Windows ( Etc.getpwuid will return nil there.) On Windows ENV["HOME"] and the methods mentioned above that rely on it , will work, despite the fact that the HOME variable will not be normally set on Windows - at startup Ruby will fill ENV["HOME"] based on the environment variables windows HOMEPATH and HOMEDRIVE . If the windows environment variables HOMEDRIVE and HOMEPATH not set, this will not work. I donโ€™t know how common this actually is in Windows environments, and I donโ€™t know any alternative that works in Windows.

+8
Dec 02
source share



All Articles