Skip to content

fix: Split up the build_request function to logical component functions to reduce method complexity #67

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 4 commits into from
Feb 21, 2020
Merged
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
58 changes: 35 additions & 23 deletions lib/ruby_http_client.rb
Original file line number Diff line number Diff line change
Expand Up @@ -141,29 +141,10 @@ def build_url(query_params: nil)
#
def build_request(name, args)
build_args(args) if args
uri = build_url(query_params: @query_params)
@http = build_http(uri.host, uri.port)
net_http = Kernel.const_get('Net::HTTP::' + name.to_s.capitalize)
@request = build_request_headers(net_http.new(uri.request_uri))
if @request_body &&
(!@request_headers.key?('Content-Type') ||
@request_headers['Content-Type'] == 'application/json')

# If body is a hash, encode it; else leave it alone
@request.body = if @request_body.class == Hash
@request_body.to_json
else
@request_body
end
@request['Content-Type'] = 'application/json'
elsif !@request_body && (name.to_s == 'post')
@request['Content-Type'] = ''
else
@request.body = @request_body
end
@http_options.each do |attribute, value|
@http.send("#{attribute}=", value)
end
# build the request & http object
build_http_request(name)
# set the content type & request body
update_content_type(name)
make_request(@http, @request)
end

Expand Down Expand Up @@ -245,6 +226,37 @@ def method_missing(name, *args, &_block)
# Add a segment to the URL
_(name)
end

private

def build_http_request(http_method)
uri = build_url(query_params: @query_params)
net_http = Kernel.const_get('Net::HTTP::' + http_method.to_s.capitalize)

@http = build_http(uri.host, uri.port)
@request = build_request_headers(net_http.new(uri.request_uri))
end

def update_content_type(http_method)
if @request_body && content_type_json?
# If body is a hash, encode it; else leave it alone
@request.body = if @request_body.class == Hash
@request_body.to_json
else
@request_body
end
@request['Content-Type'] = 'application/json'
elsif !@request_body && http_method.to_s == 'post'
@request['Content-Type'] = ''
else
@request.body = @request_body
end
end

def content_type_json?
!@request_headers.key?('Content-Type') ||
@request_headers['Content-Type'] == 'application/json'
end
# rubocop:enable Style/MethodMissingSuper
# rubocop:enable Style/MissingRespondToMissing
end
Expand Down