Method: Down::NetHttp#open

Defined in:
lib/down/net_http.rb

#open(url, *args, **options) ⇒ Object

Starts retrieving the remote file using Net::HTTP and returns an IO-like object which downloads the response body on-demand.



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
130
131
132
133
134
135
136
137
138
139
140
# File 'lib/down/net_http.rb', line 105

def open(url, *args, **options)
  options = merge_options(@options, *args, **options)

  max_redirects  = options.delete(:max_redirects)
  uri_normalizer = options.delete(:uri_normalizer)

  uri = ensure_uri(normalize_uri(url, uri_normalizer: uri_normalizer))

  # Create a Fiber that halts when response headers are received.
  request = Fiber.new do
    net_http_request(uri, options, follows_remaining: max_redirects) 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: options.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