5
6
7
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
36
|
# File 'lib/retryable.rb', line 5
def retryable(options = {}, &block)
opts = {:tries => 2, :sleep => 1, :on => StandardError, :matching => /.*/, :ensure => Proc.new {}, :exception_cb => Proc.new {}}
check_for_invalid_options(options, opts)
opts.merge!(options)
return if opts[:tries] == 0
on_exception, tries = [ opts[:on] ].flatten, opts[:tries]
retries = 0
retry_exception = nil
begin
return yield retries, retry_exception
rescue *on_exception => exception
raise unless Retryable.enabled?
raise unless exception.message =~ opts[:matching]
raise if retries+1 >= opts[:tries]
begin
sleep opts[:sleep].respond_to?(:call) ? opts[:sleep].call(retries) : opts[:sleep]
rescue *on_exception
end
retries += 1
retry_exception = exception
opts[:exception_cb].call(retry_exception)
retry
ensure
opts[:ensure].call(retries)
end
end
|