Module: WithRetries

Defined in:
lib/with_retries.rb

Overview

Generic WithRetries mixin

Instance Method Summary collapse

Instance Method Details

#with_retries(retries, operation: 'Operation', log_method: Kernel.method(:puts)) ⇒ Object

Generic with_retries method rubocop:disable Metrics/MethodLength



17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
# File 'lib/with_retries.rb', line 17

def with_retries(retries, operation: 'Operation',
                 log_method: Kernel.method(:puts))
  attempt = 1
  last_ex = nil
  loop do
    begin
      rval = yield
      last_ex = nil
      return rval if rval
    rescue WrappableError => ex
      # Stash the wrapped exception for later use
      last_ex = ex.wrapped
    end
    log_method.call "#{operation} failed #{attempt}/#{retries} attempts"
    break if (attempt += 1) > retries
  end
  log_method.call "#{operation} attempts totally failed"
  raise last_ex if last_ex
  nil
end