Class: Retriable::Retry

Inherits:
Object
  • Object
show all
Defined in:
lib/retriable/retry.rb

Instance Attribute Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize {|_self| ... } ⇒ Retry

Returns a new instance of Retry.

Yields:

  • (_self)

Yield Parameters:



11
12
13
14
15
16
17
18
19
# File 'lib/retriable/retry.rb', line 11

def initialize
  @tries      = 3
  @interval   = 0
  @timeout    = nil
  @on         = [StandardError, Timeout::Error]
  @on_retry   = nil

  yield self if block_given?
end

Instance Attribute Details

#intervalObject

Returns the value of attribute interval.



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

def interval
  @interval
end

#onObject

Returns the value of attribute on.



8
9
10
# File 'lib/retriable/retry.rb', line 8

def on
  @on
end

#on_retryObject

Returns the value of attribute on_retry.



9
10
11
# File 'lib/retriable/retry.rb', line 9

def on_retry
  @on_retry
end

#timeoutObject

Returns the value of attribute timeout.



7
8
9
# File 'lib/retriable/retry.rb', line 7

def timeout
  @timeout
end

#triesObject

Returns the value of attribute tries.



5
6
7
# File 'lib/retriable/retry.rb', line 5

def tries
  @tries
end

Instance Method Details

#performObject



21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
# File 'lib/retriable/retry.rb', line 21

def perform
  count = 0
  begin
    if @timeout
      Timeout::timeout(@timeout) { yield }
    else
      yield
    end
  rescue *[*on] => exception
    @tries -= 1
    if @tries > 0
      count += 1
      @on_retry.call(exception, count) if @on_retry
      sleep_for = @interval.respond_to?(:call) ? @interval.call(count) : @interval
      sleep sleep_for if sleep_for > 0

      retry
    else
      raise
    end
  end
end