Skip to content

Commit 875201a

Browse files
stoivoixti
authored andcommitted
Abstract timeout option parsing
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
1 parent a08972b commit 875201a

File tree

2 files changed

+34
-21
lines changed

2 files changed

+34
-21
lines changed

lib/http/chainable.rb

Lines changed: 1 addition & 21 deletions
Original file line numberDiff line numberDiff line change
@@ -95,27 +95,7 @@ def timeout(options)
9595
klass, options = case options
9696
when Numeric then [HTTP::Timeout::Global, {:global_timeout => options}]
9797
when Hash
98-
options = options.dup
99-
%i[read write connect].each do |k|
100-
next unless options.key? k
101-
102-
if options.key?("#{k}_timeout".to_sym)
103-
raise ArgumentError, "can't pass both #{k} and #{"#{k}_timeout".to_sym}"
104-
end
105-
106-
options["#{k}_timeout".to_sym] = options.delete k
107-
end
108-
109-
options.each do |key, value|
110-
unless HTTP::Timeout::PerOperation::SETTINGS.member?(key) && value.is_a?(Numeric)
111-
raise ArgumentError, "invalid option #{key.inspect}, must be numeric " \
112-
"`.timeout(connect: x, write: y, read: z)`."
113-
end
114-
end
115-
116-
raise ArgumentError, "at least one option" if options.empty?
117-
118-
[HTTP::Timeout::PerOperation, options.dup]
98+
[HTTP::Timeout::PerOperation, HTTP::Timeout::PerOperation.parse_options(options)]
11999
when :null then [HTTP::Timeout::Null, {}]
120100
else raise ArgumentError, "Use `.timeout(:null)`, " \
121101
"`.timeout(global_timeout_in_seconds)` or " \

lib/http/timeout/per_operation.rb

Lines changed: 33 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -12,6 +12,39 @@ class PerOperation < Null
1212
READ_TIMEOUT = 0.25
1313

1414
SETTINGS = Set.new(%i[read_timeout write_timeout connect_timeout])
15+
16+
class << self
17+
def parse_options(options)
18+
options = options.dup.then { |opts| expand_names(opts) }
19+
options.each do |key, value|
20+
unless SETTINGS.member?(key) && value.is_a?(Numeric)
21+
raise ArgumentError, "invalid option #{key.inspect}, must be numeric " \
22+
"`.timeout(connect: x, write: y, read: z)`."
23+
end
24+
end
25+
26+
raise ArgumentError, "at least one option" if options.empty?
27+
28+
options
29+
end
30+
31+
private
32+
33+
def expand_names(options)
34+
%i[read write connect].each do |k|
35+
next unless options.key? k
36+
37+
if options.key?("#{k}_timeout".to_sym)
38+
raise ArgumentError, "can't pass both #{k} and #{"#{k}_timeout".to_sym}"
39+
end
40+
41+
options["#{k}_timeout".to_sym] = options.delete k
42+
end
43+
44+
options
45+
end
46+
end
47+
1548
def initialize(*args)
1649
super
1750

0 commit comments

Comments
 (0)