Method: Down::NetHttp#open
- Defined in:
- lib/down/net_http.rb
#open(url, options = {}) ⇒ Object
Starts retrieving the remote file using Net::HTTP and returns an IO-like object which downloads the response body on-demand.
98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 |
# File 'lib/down/net_http.rb', line 98 def open(url, = {}) uri = ensure_uri(addressable_normalize(url)) = .merge() # Create a Fiber that halts when response headers are received. request = Fiber.new do net_http_request(uri, ) do |response| Fiber.yield response end end response = request.resume response_error!(response) unless response.is_a?(Net::HTTPSuccess) # Build an IO-like object that will retrieve response body on-demand. Down::ChunkedIO.new( chunks: enum_for(:stream_body, response), size: response["Content-Length"] && response["Content-Length"].to_i, encoding: response.type_params["charset"], rewindable: .fetch(:rewindable, true), on_close: -> { request.resume }, # close HTTP connnection data: { status: response.code.to_i, headers: response.each_header.inject({}) { |headers, (downcased_name, value)| name = downcased_name.split("-").map(&:capitalize).join("-") headers.merge!(name => value) }, response: response, }, ) end |