throttler 0.1.1 → 0.1.3

Sign up to get free protection for your applications and to get access to all the features.
Files changed (3) hide show
  1. data/lib/throttler.rb +14 -11
  2. data/spec/throttler_spec.rb +10 -1
  3. metadata +4 -3
data/lib/throttler.rb CHANGED
@@ -3,21 +3,24 @@ module Throttler
3
3
  require "fileutils"
4
4
 
5
5
  def throttle(name, interval=1.0)
6
- path = "/tmp/.#{name}"
6
+ begin
7
+ path = "/tmp/.#{name}"
7
8
 
8
- FileUtils.touch path unless File.exist? path
9
+ FileUtils.touch path unless File.exist? path
9
10
 
10
- file = File.open(path, "r+")
11
- file.flock(File::LOCK_EX)
11
+ file = File.open(path, "r+")
12
+ file.flock(File::LOCK_EX)
12
13
 
13
- last = file.gets.to_f || Time.now.to_f - interval
14
- sleep [last + interval - Time.now.to_f, 0.0].max
14
+ last = file.gets.to_f || Time.now.to_f - interval
15
+ sleep [last + interval - Time.now.to_f, 0.0].max
15
16
 
16
- yield if block_given?
17
+ yield if block_given?
17
18
 
18
- file.rewind
19
- file.write(Time.now.to_f)
20
- file.flock(File::LOCK_UN)
21
- file.close
19
+ file.rewind
20
+ file.write(Time.now.to_f)
21
+ ensure
22
+ file.flock(File::LOCK_UN)
23
+ file.close
24
+ end
22
25
  end
23
26
  end
@@ -13,6 +13,10 @@ class Foo
13
13
  throttle("baz"){ noop }
14
14
  end
15
15
 
16
+ def exceptional
17
+ throttle("bar"){ raise }
18
+ end
19
+
16
20
  def noop; end
17
21
  end
18
22
 
@@ -29,7 +33,7 @@ describe Throttler do
29
33
  end
30
34
  end
31
35
 
32
- time.should be_close 2, 0.01
36
+ time.should be_close 2, 0.1
33
37
  end
34
38
 
35
39
  it "throttles threads" do
@@ -75,4 +79,9 @@ describe Throttler do
75
79
 
76
80
  count.should eql 6
77
81
  end
82
+
83
+ it "removes lock if block raises exception" do
84
+ lambda{ Foo.new.exceptional }.should raise_error
85
+ File.open("/tmp/.bar") { |f| f.flock(File::LOCK_EX | File::LOCK_NB).should_not be_false }
86
+ end
78
87
  end
metadata CHANGED
@@ -1,16 +1,17 @@
1
1
  --- !ruby/object:Gem::Specification
2
2
  name: throttler
3
3
  version: !ruby/object:Gem::Version
4
- hash: 25
4
+ hash: 29
5
5
  prerelease: false
6
6
  segments:
7
7
  - 0
8
8
  - 1
9
- - 1
10
- version: 0.1.1
9
+ - 3
10
+ version: 0.1.3
11
11
  platform: ruby
12
12
  authors:
13
13
  - Hakan Ensari
14
+ - Piotr Laszewski
14
15
  autorequire:
15
16
  bindir: bin
16
17
  cert_chain: []