Class: Wire

Inherits:
Thread
  • Object
show all
Defined in:
lib/wire.rb

Class Method Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(args, &block) ⇒ Wire

Returns a new instance of Wire.



10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
# File 'lib/wire.rb', line 10

def initialize(args, &block)
  args.keys.each { |name| instance_variable_set "@" + name.to_s, args[name] }

  if @max.to_i <= 0 or @wait.nil?
    warn "Both max and wait needs to be passed, where max > 0. Using default values"
    @max = 10 if @max.to_i <= 0
    @wait ||= 1
  end
  
  @block   = block
  @counter = Wire.counter
  @retries ||= 0
  @retry = 0
  @delay ||= 0
  
  @counter.synchronize do
    @counter.cond.wait_until { @counter.i < @max }
    @counter.inc
  end
  
  if @counter.last and (t = Time.now.to_f - @counter.last) < @wait
    sleep (@wait - t)
  end
  
  super { runner }
end

Class Method Details

.counterObject



6
7
8
# File 'lib/wire.rb', line 6

def self.counter
  @counter ||= Counter.new
end

Instance Method Details

#report(error, message) ⇒ Object



54
55
56
# File 'lib/wire.rb', line 54

def report(error, message)
  @silent ? warn(message) : (raise error)
end

#runnerObject



37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
# File 'lib/wire.rb', line 37

def runner
  @timeout ? Timeout::timeout(@timeout) { @block.call(*@vars) } : @block.call(*@vars)
rescue StandardError => error
  if (@retry += 1) < @retries
    sleep @delay; retry
  end
  report(error, "An error occurred: #{error.inspect}")
ensure
  @counter.synchronize do
    if @max == @counter.i or @counter.last
      @counter.last = Time.now.to_f
    end
    @counter.dec
    @counter.cond.signal
  end
end