Class: Take2::Configuration

Inherits:
Object
  • Object
show all
Defined in:
lib/take2/configuration.rb

Constant Summary collapse

CONFIG_ATTRS =
[:retries,
:retriable,
:retry_proc,
:retry_condition_proc,
:time_to_sleep,
:backoff_setup,
:backoff_intervals].freeze

Instance Method Summary collapse

Constructor Details

#initialize(options = {}) ⇒ Configuration

Returns a new instance of Configuration.



17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
# File 'lib/take2/configuration.rb', line 17

def initialize(options = {})
  # Defaults
  @retries = 3
  @retriable = [
    Net::HTTPServerException,
    Net::HTTPRetriableError,
    Errno::ECONNRESET,
    IOError,
  ].freeze
  @retry_proc = proc {}
  @retry_condition_proc = proc { false }
  @time_to_sleep = 0 # TODO: Soft deprecate time to sleep
  @backoff_setup = { type: :constant, start: 3 }
  @backoff_intervals = Backoff.new(*@backoff_setup.values).intervals
  # Overwriting the defaults
  validate_options(options, &setter)
end

Instance Method Details

#[](value) ⇒ Object



41
42
43
# File 'lib/take2/configuration.rb', line 41

def [](value)
  public_send(value)
end

#assign_backoff_intervals(backoff_setup) ⇒ Object



75
76
77
# File 'lib/take2/configuration.rb', line 75

def assign_backoff_intervals(backoff_setup)
  @backoff_intervals = Backoff.new(backoff_setup[:type], backoff_setup[:start]).intervals
end

#setterObject



65
66
67
68
69
70
71
72
73
# File 'lib/take2/configuration.rb', line 65

def setter
  ->(key, value) {
    if key == :backoff_setup
      assign_backoff_intervals(value)
    else
      public_send("#{key}=", value)
    end
  }
end

#to_hashObject



35
36
37
38
39
# File 'lib/take2/configuration.rb', line 35

def to_hash
  CONFIG_ATTRS.each_with_object({}) do |key, hash|
    hash[key] = public_send(key)
  end
end

#validate_options(options) ⇒ Object



45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
# File 'lib/take2/configuration.rb', line 45

def validate_options(options)
  options.each do |k, v|
    raise ArgumentError, "#{k} is not a valid configuration" unless CONFIG_ATTRS.include?(k)
    case k
    when :retries
      raise ArgumentError, "#{k} must be positive integer" unless v.is_a?(Integer) && v.positive?
    when :time_to_sleep
      raise ArgumentError, "#{k} must be positive number" unless (v.is_a?(Integer) || v.is_a?(Float)) && v >= 0
    when :retriable
      raise ArgumentError, "#{k} must be array of retriable errors" unless v.is_a?(Array)
    when :retry_proc, :retry_condition_proc
      raise ArgumentError, "#{k} must be Proc" unless v.is_a?(Proc)
    when :backoff_setup
      available_types = [:constant, :linear, :fibonacci, :exponential]
      raise ArgumentError, 'Incorrect backoff type' unless available_types.include?(v[:type])
    end
    yield(k, v) if block_given?
  end
end