Question

I am looking for an robust, elegant and portable solution to get the user-, host- and osname in Ruby. I would like to create a folder structure which is set up like this:

linux/maschine1/user53, or
linux/maschine2/user53, or 
windows/maschine1/user53, or
mac/supermac/superuser

the name of the user- and hostname should reflect the user@computer:~$ on a linux shell and the operating system should be divided in win, linux and mac.

I found several approaches, using the ENV['USER'/'USERNAME'], or Etc.getLogin() for the username, Socket.gethostname for the computername and the RUBY_PLATFORM constant for the os-name. But all of them have issues when running in different Plattforms like JRuby or even on different operating systems.

So which choice would be the best for each?

Thanks!

Edit:

I came to this solution a short moment before the answer was given. Since Buildr can also use Java commands it is possible to get the values like this:

os = Java.java.lang.System.getProperty('os.name')
usr = Java.java.lang.System.getProperty('user.name')
host = Java.java.net.InetAddress.getLocalHost().getHostName()

But I think I am going to use the pure ruby way to keep the language as consistent as possible.

Was it helpful?

Solution

Not sure there is really a gem that does it all, but Etc.getlogin and Socket.getshostname should work across platforms I think. I use this or variations of to get the os:

require 'rbconfig'

  def os
    @os ||= (
      host_os = RbConfig::CONFIG['host_os']
      case host_os
      when /mswin|msys|mingw|cygwin|bccwin|wince|emc/
        :windows
      when /darwin|mac os/
        :macosx
      when /linux/
        :linux
      when /solaris|bsd/
        :unix
      else
        raise "unknown os: #{host_os.inspect}"
      end
    )
  end

which is ripped off from the selenium gem: https://code.google.com/p/selenium/source/browse/rb/lib/selenium/webdriver/common/platform.rb which might provide a bit more inspiration.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top