Ruby: How to check the operating system

Posted by luca
on Friday, October 05

Today I'm finishing the code cleanup for my latest Rails plugin (will be soon released) and I want to execute some rake tasks, only if the OS supports certain system calls.

The following snippet helps to check the current platform.

# (c) 2007 Luca Guidi (www.lucaguidi.com) - Released under MIT License.
# This code was inspired by Prototype rake test tasks.
require 'webrick'

class OperatingSystem
  class << self
    def host
      Config::CONFIG['host']
    end
  
    def macos?
      host.include?('darwin')
    end

    def linux?
      host.include?('linux')
    end
  
    def windows?
      host.include?('mswin')
    end
    
    def current
      case 
        when macos?:   'macos'
        when linux?:   'linux'
        when windows?: 'windows'
        else           'unknown'
      end
    end
  end
end