Module: Retryable

Defined in:
lib/retryable.rb,
lib/retryable/version.rb,
lib/retryable/configuration.rb

Defined Under Namespace

Classes: Configuration, Version

Class Attribute Summary collapse

Class Method Summary collapse

Class Attribute Details

.configurationObject

The configuration object.

See Also:



27
28
29
# File 'lib/retryable.rb', line 27

def configuration
  @configuration ||= Configuration.new
end

Class Method Details

.configure {|configuration| ... } ⇒ Object

Call this method to modify defaults in your initializers.

Examples:

Retryable.configure do |config|
  config.ensure       = Proc.new {}
  config.exception_cb = Proc.new {}
  config.matching     = /.*/
  config.on           = StandardError
  config.sleep        = 1
  config.tries        = 2
end

Yields:



21
22
23
# File 'lib/retryable.rb', line 21

def configure
  yield(configuration)
end

.disableObject



39
40
41
# File 'lib/retryable.rb', line 39

def disable
  configuration.disable
end

.enableObject



35
36
37
# File 'lib/retryable.rb', line 35

def enable
  configuration.enable
end

.enabled?Boolean

Returns:

  • (Boolean)


31
32
33
# File 'lib/retryable.rb', line 31

def enabled?
  configuration.enabled?
end

.retryable(options = {}, &block) ⇒ Object



43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
# File 'lib/retryable.rb', line 43

def retryable(options = {}, &block)
  opts = {
    :tries        => self.configuration.tries,
    :sleep        => self.configuration.sleep,
    :on           => self.configuration.on,
    :matching     => self.configuration.matching,
    :ensure       => self.configuration.ensure,
    :exception_cb => self.configuration.exception_cb
  }

  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 configuration.enabled?
    raise unless exception.message =~ opts[:matching]
    raise if retries+1 >= tries

    # Interrupt Exception could be raised while sleeping
    begin
      Kernel.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