Proper way to detect Windows platform in Ruby
I’ve seen this time and again, the Windows platform detection in Ruby is typically done like this: RUBY_PLATFORM =~ /mswin/. THIS IS WRONG! First, there is also mingw version of Ruby on Windows. So, folks started to use the updated check pattern: RUBY_PLATFORM =~ /mswin|mingw/. THIS IS WRONG TOO! There are other implementations of Ruby, like JRuby and IronRuby. And in JRuby the RUBY_PLATFORM value is “java”, it is platform-independent value, expressing one of the core JRuby properties – it is built on top of Java platform. Plus, every time new implementation comes along, all old checks would be obsolete once again.
Now, the proper way to check the Windows platform, which is surprisingly less-known. Use rbconfig!
require ‘rbconfig’
WINDOZE = Config::CONFIG[‘host_os’] =~ /mswin|mingw/
This will work for x32 and x64 versions of Ruby, for mingw-based Ruby, for IronRuby, and for reasonably fresh JRuby (1.3.1, 1.4, 1.5+) as well. Please, please, update your sources!
November 4th, 2009 at 7:07 pm
Ah nice one. I’m no Ruby expert, but use it for builds and acceptance testing (cucumber/watir) in our .Net environment.
We’re switching architecture at the moment, so it’s something I need to know for the build. Was close to doing it the way you mention not to.
Great tip.
November 9th, 2009 at 5:27 pm
Here’s how I currently do it
$ gem install sane
then
require ’sane/os’ # ok so it’s my own gem
OS.windows?
November 15th, 2009 at 3:57 pm
[...] Proper way to detect Windows platform in Ruby – The Empty Way [...]