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 8, 2023
1 parent c5b9a7f commit 618641e
Show file tree
Hide file tree
Showing 2 changed files with 33 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 @@ -95,27 +95,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
32 changes: 32 additions & 0 deletions lib/http/timeout/per_operation.rb
Original file line number Diff line number Diff line change
Expand Up @@ -20,6 +20,38 @@ def initialize(*args)
@connect_timeout = options.fetch(:connect_timeout, CONNECT_TIMEOUT)
end

class << self
def parse_options(options)
options = options.dup.then { |opts| undo_short_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 undo_short_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 connect(socket_class, host, port, nodelay = false)
::Timeout.timeout(@connect_timeout, ConnectTimeoutError) do
@socket = socket_class.open(host, port)
Expand Down

0 comments on commit 618641e

Please sign in to comment.