Can I make my extconf.rb behave differently depending on the operating system?

I want my Ruby program to do different things on a Mac than on Windows. How can I find out on which system my program is running?

Replay

Use the RUBY_PLATFORM constant, and optionally wrap it in a module to make it more friendly:

module OS
  def OS.windows?
    (/cygwin|mswin|mingw|bccwin|wince|emx/ =~ RUBY_PLATFORM) != nil
  end

  def OS.mac?
   (/darwin/ =~ RUBY_PLATFORM) != nil
  end

  def OS.unix?
    !OS.windows?
  end

  def OS.linux?
    OS.unix? and not OS.mac?
  end
end

It is not perfect, but works well for the platforms that I do development on, and it's easy enough to extend.

Either

irb(main):002:0> require 'rbconfig'
=> true
irb(main):003:0> Config::CONFIG["arch"]
=> "i686-linux"

or

irb(main):004:0> RUBY_PLATFORM
=> "i686-linux"

Try the Launchy gem (gem install launchy):

require 'launchy'
Launchy::Application.new.host_os_family # => :windows, :darwin, :nix, or :cygwin

(Warning: read @Peter Wagenet's comment ) I like this, most people use rubygems, its reliable, is cross platform

irb(main):001:0> Gem::Platform.local
=> #<Gem::Platform:0x151ea14 @cpu="x86", @os="mingw32", @version=nil>
irb(main):002:0> Gem::Platform.local.os
=> "mingw32"

require 'rbconfig'
include Config

case CONFIG['host_os']
  when /mswin|windows/i
    # Windows
  when /linux|arch/i
    # Linux
  when /sunos|solaris/i
    # Solaris
  when /darwin/i
    #MAC OS X
  else
    # whatever
end

We have been doing pretty good so far with the following code

  def self.windows?
    return File.exist? "c:/WINDOWS" if RUBY_PLATFORM == 'java'
    RUBY_PLATFORM =~ /mingw32/ || RUBY_PLATFORM =~ /mswin32/
  end

  def self.linux?
    return File.exist? "/usr" if RUBY_PLATFORM == 'java'
    RUBY_PLATFORM =~ /linux/
  end

  def self.os
    return :linux if self.linux?
    return :windows if self.windows?
    nil
  end

I have a second answer, to add more options to the fray. The os rubygem, and the github page has a related projects list.

require 'os'

>> OS.windows?
=> true   # or OS.doze?

>> OS.bits
=> 32

>> OS.java?
=> true # if you're running in jruby.  Also OS.jruby?

>> OS.ruby_bin
=> "c:\ruby18\bin\ruby.exe" # or "/usr/local/bin/ruby" or what not

>> OS.posix?
=> false # true for linux, os x, cygwin

>> OS.mac? # or OS.osx? or OS.x?
=> false

When I just need to know if it is a Windows or Unix-like OS it is often enough to

is_unix = is_win = false
File::SEPARATOR == '/' ? is_unix = true : is_win = true

Category: ruby Time: 2008-10-04 Views: 1

Related post

iOS development

Android development

Python development

JAVA development

Development language

PHP development

Ruby development

search

Front-end development

Database

development tools

Open Platform

Javascript development

.NET development

cloud computing

server

Copyright (C) avrocks.com, All Rights Reserved.

processed in 0.208 (s). 12 q(s)