From 6dcaa1895ea93140b074f951b156e3f8ef05a069 Mon Sep 17 00:00:00 2001 From: Sam Rawlins Date: Sat, 22 Feb 2014 21:43:58 -0800 Subject: [PATCH] Adding block functionality to HTTP.get --- lib/net/http.rb | 20 ++++++++++++++++++-- test/net/http/test_http.rb | 7 +++++++ 2 files changed, 25 insertions(+), 2 deletions(-) diff --git a/lib/net/http.rb b/lib/net/http.rb index 6d6a24f..145bf42 100644 --- a/lib/net/http.rb +++ b/lib/net/http.rb @@ -451,8 +451,24 @@ def HTTP.get_print(uri_or_host, path = nil, port = nil) # # print Net::HTTP.get('www.example.com', '/index.html') # - def HTTP.get(uri_or_host, path = nil, port = nil) - get_response(uri_or_host, path, port).body + # If called with a block, yields each fragment of the + # entity body in turn as a String as it is read from + # the socket. Note that in this case, the returned response + # object will *not* contain a (meaningful) body. + # + # File.open('result.zip', 'wb') {|f| + # Net::HTTP.get('www.example.com', '/file.zip') do |chunk| + # f.write chunk + # end + # } + def HTTP.get(uri_or_host, path = nil, port = nil, &block) + if block_given? + get_response(uri_or_host, path, port) {|res| + res.read_body &block + } + else + get_response(uri_or_host, path, port).body + end end # Sends a GET request to the target and returns the HTTP response diff --git a/test/net/http/test_http.rb b/test/net/http/test_http.rb index 6c847db..c899aaa 100644 --- a/test/net/http/test_http.rb +++ b/test/net/http/test_http.rb @@ -196,6 +196,13 @@ module TestNetHTTP_version_1_1_methods def test_s_get assert_equal $test_net_http_data, Net::HTTP.get(config('host'), '/', config('port')) + + f = StringIO.new("".force_encoding("ASCII-8BIT")) + Net::HTTP.get(config('host'), '/', config('port')) do |chunk| + f.write chunk + end + + assert_equal $test_net_http_data, f.string end def test_head -- 1.8.5.5