Class: Batsir::Strategies::RetryStrategy

Inherits:
Strategy
  • Object
show all
Includes:
Log
Defined in:
lib/batsir/strategies/retry_strategy.rb

Instance Attribute Summary collapse

Attributes inherited from Strategy

#context

Instance Method Summary collapse

Methods included from Log

#log

Constructor Details

#initialize(context, retries = 3) ⇒ RetryStrategy

Returns a new instance of RetryStrategy.



8
9
10
11
12
# File 'lib/batsir/strategies/retry_strategy.rb', line 8

def initialize(context, retries = 3)
  super(context)
  @retries  = retries
  @attempts = {}
end

Instance Attribute Details

#attemptsObject (readonly)

Returns the value of attribute attempts.



6
7
8
# File 'lib/batsir/strategies/retry_strategy.rb', line 6

def attempts
  @attempts
end

#retriesObject (readonly)

Returns the value of attribute retries.



6
7
8
# File 'lib/batsir/strategies/retry_strategy.rb', line 6

def retries
  @retries
end

Instance Method Details

#execute(message, error) ⇒ Object



14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
# File 'lib/batsir/strategies/retry_strategy.rb', line 14

def execute(message, error)
  @attempts[message] ? @attempts[message] += 1 : @attempts[message] = 0

  if @attempts[message] >= @retries
    error_msg = "Tried to send '#{message}' #{@attempts[message]} times and failed"
    reset_attempts(message)
    log.error error_msg
    raise Batsir::Errors::RetryStrategyFailed.new error_msg
  else
    log.warn "Recovering from #{error}. Making another attempt (##{@attempts[message]+1})"
    result = @context.execute(message)
    reset_attempts(message)
    return result
  end
end

#reset_attempts(message) ⇒ Object



30
31
32
# File 'lib/batsir/strategies/retry_strategy.rb', line 30

def reset_attempts(message)
  @attempts.delete(message)
end