Add Hermann::Timeout abstraction for 1.8/1.9 compatible timeout support

This commit is contained in:
R. Tyler Croy 2014-09-09 14:18:41 -07:00
parent 0f9681ab91
commit 4d7e9f3b4e
4 changed files with 71 additions and 0 deletions

View File

@ -7,4 +7,5 @@ gem 'pry'
group :test do
gem 'rspec', '~> 3.0.0'
gem 'rspec-its'
gem 'system_timer', :platform => :mri_18
end

View File

@ -27,6 +27,7 @@ GEM
rspec-support (~> 3.0.0)
rspec-support (3.0.4)
slop (3.5.0)
system_timer (1.2.4)
PLATFORMS
ruby
@ -37,3 +38,4 @@ DEPENDENCIES
rake-compiler
rspec (~> 3.0.0)
rspec-its
system_timer

37
lib/hermann/timeout.rb Normal file
View File

@ -0,0 +1,37 @@
begin
require 'system_timer'
module Hermann
class Timeout
USE_SYSTEM_TIMER = true
end
end
rescue LoadError
require 'timeout'
if RUBY_VERSION == '1.8.7'
puts ">>> You are running on 1.8.7 without SystemTimer"
puts ">>> which means Hermann::Timeout will not work as expected"
end
module Hermann
class Timeout
USE_SYSTEM_TIMER = false
end
end
end
module Hermann
class Timeout
def self.system_timer?
Hermann::Timeout::USE_SYSTEM_TIMER
end
def self.timeout(seconds, klass=nil, &block)
if system_timer?
SystemTimer.timeout_after(seconds, klass, &block)
else
::Timeout.timeout(seconds, klass, &block)
end
end
end
end

31
spec/timeout_spec.rb Normal file
View File

@ -0,0 +1,31 @@
require 'spec_helper'
require 'hermann/timeout'
# Forward declare the module so this will work even without SystemTimer
# installed (e.g. non-1.8.7)
module SystemTimer; end
describe Hermann::Timeout do
describe '#timeout' do
let(:seconds) { 5 }
let(:result) { 'rspec' }
subject(:timeout!) { described_class.timeout(seconds) { result } }
context 'with system_timer' do
before :each do
expect(described_class).to receive(:system_timer?).and_return(true)
expect(SystemTimer).to receive(:timeout_after).and_return(result)
end
it { should eql(result) }
end
context 'without system_timer' do
before :each do
expect(described_class).to receive(:system_timer?).and_return(false)
end
it { should eql(result) }
end
end
end