Module: RbTryagain

Defined in:
lib/rb_tryagain.rb,
lib/rb_tryagain/version.rb

Constant Summary collapse

VERSION =
"0.0.1"

Class Method Summary collapse

Class Method Details

.try_again(args = {}, &block) ⇒ Object



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
# File 'lib/rb_tryagain.rb', line 5

def try_again(args = {}, &block)
  max_tries = args[:tries] || 5
  on_error = args[:on_error] || :raise
  print_errors = args[:print_errors] || false
  current_tries = 0
  
  success = false
  until current_tries >= max_tries or success
    begin
      block.call
    rescue Exception => ex
      if print_errors
        STDERR.puts ex.message
        STDERR.puts ex.backtrace
      end
      current_tries += 1
      
      if current_tries >= max_tries and on_error == :raise
        raise ex
      end
    else
      success = true
    end
  end
end