Class: DefRetry::Retrier
- Inherits:
-
Object
- Object
- DefRetry::Retrier
- Defined in:
- lib/def_retry/retrier.rb
Constant Summary collapse
- DEFAULT_TRIES =
3- SLEEP_STRATEGIES =
{ constant: ->(n) { 1 }, linear: ->(n) { n }, exponential: ->(n) { n**2 } }
Instance Method Summary collapse
-
#initialize(options) ⇒ Retrier
constructor
A new instance of Retrier.
- #run(&block) ⇒ Object
Constructor Details
#initialize(options) ⇒ Retrier
Returns a new instance of Retrier.
10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 |
# File 'lib/def_retry/retrier.rb', line 10 def initialize() @args = .fetch :args, [] @tries = .fetch :tries, DEFAULT_TRIES @on_retry = .fetch :on_retry, ->(e, n) {} @on_ensure = .fetch :on_ensure, ->(r, n) {} @re_raise = .fetch :re_raise, true @sleep = .fetch :sleep, false begin @sleep = SLEEP_STRATEGIES.fetch @sleep if @sleep.is_a? Symbol rescue KeyError raise ArgumentError, "The :sleep option must be an Integer, a Proc, or a Symbol: #{SLEEP_STRATEGIES.keys.join(', ')}" end begin @exceptions = Array .fetch(:on) rescue KeyError raise ArgumentError, 'You must specify which exceptions to retry :on' end end |
Instance Method Details
#run(&block) ⇒ Object
31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 |
# File 'lib/def_retry/retrier.rb', line 31 def run(&block) @try_count = 0 @return = nil begin @return = block.call *@args rescue *@exceptions => e @try_count += 1 run_sleep_strategy if @sleep @on_retry.call e, @try_count @try_count < @tries ? retry : (@re_raise and raise) ensure @on_ensure.call @return, @try_count @return end end |