Skip to content

Commit

Permalink
Abstract timeout option parsing
Browse files Browse the repository at this point in the history
Rubocop told me the method started to be too complex.

lib/http/chainable.rb:94:5: C: Metrics/PerceivedComplexity: Perceived complexity for timeout is too high. [10/8]
    def timeout(options) ...
    ^^^^^^^^^^^^^^^^^^^^
80 files inspected, 1 offense detected
  • Loading branch information
stoivo committed Jun 9, 2023
1 parent 0b150cb commit aa9451f
Show file tree
Hide file tree
Showing 2 changed files with 34 additions and 21 deletions.
22 changes: 1 addition & 21 deletions lib/http/chainable.rb
Original file line number Diff line number Diff line change
Expand Up @@ -94,27 +94,7 @@ def timeout(options)
klass, options = case options
when Numeric then [HTTP::Timeout::Global, {:global_timeout => options}]
when Hash
options = options.dup
%i[read write connect].each do |k|
next unless options.key? k

if options.key?("#{k}_timeout".to_sym)
raise ArgumentError, "can't pass both #{k} and #{"#{k}_timeout".to_sym}"
end

options["#{k}_timeout".to_sym] = options.delete k
end

options.each do |key, value|
unless HTTP::Timeout::PerOperation::SETTINGS.member?(key) && value.is_a?(Numeric)
raise ArgumentError, "invalid option #{key.inspect}, must be numeric " \
"`.timeout(connect: x, write: y, read: z)`."
end
end

raise ArgumentError, "at least one option" if options.empty?

[HTTP::Timeout::PerOperation, options.dup]
[HTTP::Timeout::PerOperation, HTTP::Timeout::PerOperation.parse_options(options)]
when :null then [HTTP::Timeout::Null, {}]
else raise ArgumentError, "Use `.timeout(:null)`, " \
"`.timeout(global_timeout_in_seconds)` or " \
Expand Down
33 changes: 33 additions & 0 deletions lib/http/timeout/per_operation.rb
Original file line number Diff line number Diff line change
Expand Up @@ -12,6 +12,39 @@ class PerOperation < Null
READ_TIMEOUT = 0.25

SETTINGS = Set.new(%i[read_timeout write_timeout connect_timeout])

class << self
def parse_options(options)
options = options.dup.then { |opts| expand_names(opts) }
options.each do |key, value|
unless SETTINGS.member?(key) && value.is_a?(Numeric)
raise ArgumentError, "invalid option #{key.inspect}, must be numeric " \
"`.timeout(connect: x, write: y, read: z)`."
end
end

raise ArgumentError, "at least one option" if options.empty?

options
end

private

def expand_names(options)
%i[read write connect].each do |k|
next unless options.key? k

if options.key?("#{k}_timeout".to_sym)
raise ArgumentError, "can't pass both #{k} and #{"#{k}_timeout".to_sym}"
end

options["#{k}_timeout".to_sym] = options.delete k
end

options
end
end

def initialize(*args)
super

Expand Down

0 comments on commit aa9451f

Please sign in to comment.