Class: Numeric

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

Overview

Extend the Numeric class with a #tries method

Instance Method Summary collapse

Instance Method Details

#tries(rescue_from: [StandardError]) ⇒ Object Also known as: try

rubocop:disable Metrics/MethodLength

Raises:

  • (ArgumentError)


8
9
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/easy_retry.rb', line 8

def tries(rescue_from: [StandardError])
  raise ArgumentError, 'No block given' unless block_given?

  rescue_from = Array(rescue_from)
  max_retry = self
  current_try = 1
  result = nil

  loop do
    result = yield(current_try)

    break
  rescue *rescue_from => e
    if defined?(Rails)
      Rails.logger.error "Error: #{e.message} (#{current_try}/#{max_retry})"
    else
      puts "Error: #{e.message} (#{current_try}/#{max_retry})"
    end

    raise if current_try >= max_retry

    sleep current_try * current_try

    current_try += 1
  end

  result
end