Reliable timeout for Ruby 1.8.x with fallback

We want reliable timeouts, but dont want to hard-code SystemTimer everywhere, so atm we are using this:

# lib/safe_timeout.rb
# stolen from klarlack --
# to get an reliable timeout that wont fail on other platforms
# or if sytem_timer is missing
SafeTimeout = begin
  # Try to use the SystemTimer gem instead of Ruby's timeout library
  # when running on something that looks like Ruby 1.8.x. See:
  # We don't want to bother trying to load SystemTimer on jruby and
  # ruby 1.9+.
  if RUBY_VERSION =~ /^1\.8\./ and RUBY_PLATFORM !~ /java/
    require 'system_timer'
    require 'timeout'
rescue LoadError => e
  $stderr.puts "Could not load SystemTimer gem, falling back to Ruby's slower/unsafe timeout library: #{e.message}"
  require 'timeout'

Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s