Reputation: 362786
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.
Upvotes: 0
Views: 353
Reputation: 42192
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:
Upvotes: 2
Reputation: 34031
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
Upvotes: 1