0

I am using colored gem for coloured printing in the terminal and ruby logger. I need to run this code on linux and on windows.

On windows, I must first require 'win32console' or else coloured printing doesn't work (I just see ANSI escape characters instead). But if I require win32console on linux it breaks, obviously.

What's the usual way to handle a situation like this in ruby? I noticed the RUBY_PLATFORM variable, but on a windows VM I tried it was "i386-mingw32" or something strange. Using that plus a conditional seems like a pretty flakey way to go about what I need, so I was hoping this problem has a better solution.

wim
  • 338,267
  • 99
  • 616
  • 750
  • Are you looking for the OS? If so this may be helpful: http://stackoverflow.com/questions/170956/how-can-i-find-which-operating-system-my-ruby-program-is-running-on – squiguy Apr 09 '13 at 06:47
  • Yep, I saw that question. The answer there is the kind of thing I thought seemed kinda cheap and flakey .. – wim Apr 09 '13 at 06:51

2 Answers2

2

Nothing wrong with using RUBY_PLATFORM, it is its purpose. You could also ask it the OS itself, for windows that would be

ENV['OS']

Which gives "Windows_NT" on a Vista.

Don't know the counterpart for the other OS.

See also:

Community
  • 1
  • 1
peter
  • 41,770
  • 5
  • 64
  • 108
1

There's always:

begin
  require 'win32console'
rescue LoadError
end

I find this easier to write and reason about that trying to decide for myself which OS I'm on and whether or not to load it.

Update: I was thinking win32console was built-in rather than a gem. I believe Win32API is available on all Windows installs, so it's a good proxy to test "Is this Windows?" (rather than "What OS is this, and is that Windows?").

begin
  require 'Win32API'
  windowsOS = true
rescue LoadError
  windowsOS = false
end

if windowsOS
  begin
    require 'win32console'
  rescue LoadError
    # Prompt user to install win32console gem
  end
end
Darshan Rivka Whittle
  • 32,989
  • 7
  • 91
  • 109
  • I considered this approach, but it would also mean that the windows users would silently fail if they didn't have 'win32console' gem. So I still need a way to differentiate between those windows users, who should go and install the gem, and the linux users who can safely ignore the LoadError – wim Apr 09 '13 at 07:23
  • 1
    @wim Sorry, I was thinking win32console was part of the Ruby install. I'm fairly certain Win32API in fact is, so I've updated my answer. – Darshan Rivka Whittle Apr 09 '13 at 07:42
  • Thanks, this looks like a nicer alternative, provided there's not too much overhead in the otherwise unneeded `require 'Win32API'` – wim Apr 09 '13 at 08:18