rulururu

post Determine OS with ruby

June 1st, 2009

Filed under: Ruby — Kai @ 6:30 pm

I’m developing a tiny application that should run on (almost) any operating system. Though to that I sometimes have to do some switches (e.g. for console coloring).
The constant RUBY_PLATFORM helps me, so that I wrote a small module

module OsHelper
 
  def is_linux?
     RUBY_PLATFORM.downcase.include?("linux")
  end
 
  def is_windows?
     RUBY_PLATFORM.downcase.include?("mswin")
  end
 
  def is_mac?
    RUBY_PLATFORM.downcase.include?("darwin")
  end
 
end

Unfortunately I quickly realized that it’s more a bad than a good idea because RUBY_PLATFORM will return 'java' when using JRuby for example.

I found sys-uname library that gives much more information than that constant can do. (gem install sys-uname)

Finally you can use it like that:

begin # use Sys::Uname library if present
        require 'sys/uname'
        @@os_name = Sys::Uname.sysname
        @@architecture = Sys::Uname.machine
        @@os_version = Sys::Uname.release
      rescue # otherwise use shell
        @@os_name = `uname -s`.strip
        @@architecture = `uname -p`.strip
        @@os_version = `uname -r`.strip
      end

I hope it someday will help someone ;)

ruldrurd
Powered by WordPress, Content and Design by Kai Bellmann
Entries (RSS) and Comments (RSS)