Permalink
Browse files

Extracted request_setup from request

The work of creating a header from a URI does not need to be in #request
so this reduces the line count of request by quite a bit and makes it
easier to read.

Still, #request is weighed down by lots of exception handling
boilerplate.
  • Loading branch information...
1 parent b772eb9 commit 8d8c9065b25d044bfbf2f5a3ce8198ef9429ec6a @drbrain committed Feb 9, 2013
Showing with 57 additions and 14 deletions.
  1. +30 −14 lib/net/http/persistent.rb
  2. +27 −0 test/test_net_http_persistent.rb
View
@@ -917,20 +917,7 @@ def request uri, req = nil, &block
retried = false
bad_response = false
- req = Net::HTTP::Get.new uri.request_uri unless req
-
- @headers.each do |pair|
- req.add_field(*pair)
- end
-
- @override_headers.each do |name, value|
- req[name] = value
- end
-
- unless req['Connection'] then
- req.add_field 'Connection', 'keep-alive'
- req.add_field 'Keep-Alive', @keep_alive
- end
+ req = request_setup req || uri
connection = connection_for uri
connection_id = connection.object_id
@@ -989,6 +976,35 @@ def request_failed exception, req, connection # :nodoc:
raise Error, "too many connection resets #{due_to} #{message}"
end
+ ##
+ # Creates a GET request if +req_or_uri+ is a URI and adds headers to the
+ # request.
+ #
+ # Returns the request.
+
+ def request_setup req_or_uri # :nodoc:
+ req = if URI === req_or_uri then
+ Net::HTTP::Get.new req_or_uri.request_uri
+ else
+ req_or_uri
+ end
+
+ @headers.each do |pair|
+ req.add_field(*pair)
+ end
+
+ @override_headers.each do |name, value|
+ req[name] = value
+ end
+
+ unless req['Connection'] then
+ req.add_field 'Connection', 'keep-alive'
+ req.add_field 'Keep-Alive', @keep_alive
+ end
+
+ req
+ end
+
##
# Shuts down all connections for +thread+.
#
@@ -1167,6 +1167,33 @@ def c.request(*)
assert_match %r%bad write retry%, e.message
end
+ def test_request_setup
+ @http.override_headers['user-agent'] = 'test ua'
+ @http.headers['accept'] = 'text/*'
+
+ input = Net::HTTP::Post.new '/path'
+
+ req = @http.request_setup input
+
+ assert_same input, req
+ assert_equal '/path', req.path
+
+ assert_equal 'test ua', req['user-agent']
+ assert_match %r%text/\*%, req['accept']
+
+ assert_equal 'keep-alive', req['connection']
+ assert_equal '30', req['keep-alive']
+ end
+
+ def test_request_setup_uri
+ uri = @uri + '?a=b'
+
+ req = @http.request_setup uri
+
+ assert_kind_of Net::HTTP::Get, req
+ assert_equal '/path?a=b', req.path
+ end
+
def test_reset
c = basic_connection
c.start

0 comments on commit 8d8c906

Please sign in to comment.