lib/patiently_try.rb in patiently_try-0.2.1 vs lib/patiently_try.rb in patiently_try-0.2.2
- old
+ new
@@ -1,38 +1,71 @@
require "patiently_try/version"
module PatientlyTry
def patiently_try(opts = {})
- retries = opts[:retries] || 100
- wait = opts[:wait] || 0
- catch_errors = Array(opts[:catch] || StandardError)
- excluded_errors = Array(opts[:raise_if_caught])
- logging = opts[:logging].nil? ? true : opts[:logging]
- try = 0
+ opts = _parse_opts(opts)
+ try = 0
begin
yield
- rescue *(catch_errors) => e
+ rescue *(opts[:catch]) => e
try += 1
- _log_error(e) if logging
+ _rescue_or_raise(e, try, opts)
- if try >= retries || _rescued_but_excluded?(e, excluded_errors)
- _log_backtrace(e) if logging
- raise e
- end
+ _wait(opts[:wait])
+ retry
+ end
+ end
- _log_retry(e) if logging
+ private
- sleep wait if wait && wait > 0
+ def _rescue_or_raise(e, try, opts)
+ if opts[:logging]
+ _rescue_or_raise_with_logging(e, try, opts)
+ else
+ _rescue_or_raise_without_logging(e, try, opts)
+ end
+ end
- retry
+ def _rescue_or_raise_with_logging(e, try, opts)
+ _log_error(e) if opts[:logging]
+
+ if _should_raise?(e, try, opts)
+ _log_backtrace(e) if opts[:logging]
+ raise e
end
+
+ _log_retry(try, opts[:retries]) if opts[:logging]
end
- private
+ def _rescue_or_raise_without_logging(e, try, opts)
+ raise e if _should_raise?(e, try, opts)
+ end
- def _log_retry
+ def _should_raise?(e, try, opts)
+ _exceeded_retries?(try, opts[:retries]) || _rescued_but_excluded?(e, opts[:raise_if_caught])
+ end
+
+ def _parse_opts(opts)
+ {
+ catch: Array(opts[:catch] || StandardError),
+ raise_if_caught: Array(opts[:raise_if_caught]),
+ wait: opts[:wait].to_i,
+ logging: opts[:logging].nil? ? true : opts[:logging],
+ retries: opts[:retries] || 100
+ }
+ end
+
+ def _wait(wait_time)
+ sleep wait_time if wait_time > 0
+ end
+
+ def _exceeded_retries?(try, retries)
+ try >= retries
+ end
+
+ def _log_retry(try, retries)
puts "Retrying (#{try}/#{retries})"
end
def _rescued_but_excluded?(e, excluded_errors)
excluded_errors.to_a.inject(false) { |excl, error| excl || e.is_a?(error) }