Easily define Take2 🎬 to retry API calls, methods, or just a block of code.
RubyMIT
Take2
Define rules for retrying behavior.
Yield block of code into the with_retry method.
Things getting take two :)
Install
geminstalltake2
Examples
classServiceincludeTake2number_of_retries3# Could be configured globally or on class level.retriable_errorsNet::HTTPRetriableError,Errno::ECONNRESET# Retry unless the response status is 5xx. The implementation is dependent of the http lib in use.retriable_conditionproc{ |error| error.response.code < 500}# Defines callable code to run before next retry. Could be an out put to some logger.on_retryproc{ |error,tries| puts"#{name} - Retrying.. #{tries} of #{retriable_configuration[:retries]} (#{error})"}# The available strategies are:# type :constant, start: 2 => [2, 2, 2, 2 ... ]# type :linear, start: 3, factor: 2 => [3, 6, 12, 24 ... ]# type :fibonacci, start: 2 => [2, 3, 5, 8, 13 ... ]# type :exponential, start: 3 => [3, 7, 12, 28, 47 ... ]backoff_strategytype: :fibonacci,start: 3class << selfdefcallwith_retrydo# Some logic that might raise..# If it will raise retriable, magic happens.# If not the original error re raisedraiseNet::HTTPRetriableError.new('Release the Kraken...many times!!',nil)endend# Pass custom options per method call# The class defaults will not be overwrittendefread(file)with_retry(retries: 2,retriable: [IOError],retry_proc: proc{},retry_condition_proc: proc{})do# Some logic that might raise..endendendendService.call#=> KratosService - Retrying.. 3 of 3 (Release the Kraken...many times!!)#=> KratosService - Retrying.. 2 of 3 (Release the Kraken...many times!!)#=> KratosService - Retrying.. 1 of 3 (Release the Kraken...many times!!)# After the retrying is done, original error re-raised #=> Net::HTTPRetriableError: Release the Kraken...many times!!# Current configuration hashService.retriable_configuration