Class: URI::HTTP

Inherits:
Object
  • Object
show all
Defined in:
lib/contrib/uri_ext.rb

Overview

:nodoc:

Instance Method Summary collapse

Instance Method Details

#read(options = nil, &block) ⇒ Object

See URI::Generic#read



232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
# File 'lib/contrib/uri_ext.rb', line 232

def read(options = nil, &block)
  options ||= {}
  connect do |http|
    puts "Requesting #{self}" #if verbose
    headers = { 'If-Modified-Since' => CGI.rfc1123_date(options[:modified].utc) } if options[:modified]
    request = Net::HTTP::Get.new(request_uri.empty? ? '/' : request_uri, headers)
    request.basic_auth self.user, self.password if self.user
    http.request request do |response|
      case response
      when Net::HTTPNotModified
        # No modification, nothing to do.
        puts 'Not modified since last download' #if verbose
        return nil
      when Net::HTTPRedirection
        # Try to download from the new URI, handle relative redirects.
        puts "Redirected to #{response['Location']}" #if verbose
        return (self + URI.parse(response['location'])).read(options, &block)
      when Net::HTTPOK
        puts "Downloading #{self}" #if verbose
        result = nil
        with_progress_bar options[:progress], path.split('/').last, response.content_length do |progress|
          if block
            response.read_body do |chunk|
              block.call chunk
              progress << chunk
            end
          else
            result = ''
            response.read_body do |chunk|
              result << chunk
              progress << chunk
            end
          end
        end
        return result
      when Net::HTTPNotFound
        raise NotFoundError, "Looking for #{self} and all I got was a 404!"
      else
        raise RuntimeError, "Failed to download #{self}: #{response.message}"
      end
    end
  end
end