3
4
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
37
38
39
|
# File 'lib/tins/attempt.rb', line 3
def attempt(opts = {}, &block)
sleep = nil
exception_class = StandardError
if Numeric === opts
attempts = opts
else
attempts = opts[:attempts] || 1
exception_class = opts[:exception_class] if opts.key?(:exception_class)
sleep = opts[:sleep]
reraise = opts[:reraise]
end
return if attempts <= 0
count = 0
if exception_class.nil?
begin
count += 1
if block.call(count)
return true
elsif count < attempts
sleep_duration(sleep, count)
end
end until count == attempts
false
else
begin
count += 1
block.call(count)
true
rescue exception_class
if count < attempts
sleep_duration(sleep, count)
retry
end
reraise ? raise : false
end
end
end
|