Module: ImageSize::URIReader

Extended by:
HTTPChunkyReader
Defined in:
lib/image_size/uri_reader.rb

Overview

:nodoc:

Defined Under Namespace

Modules: HTTPChunkyReader Classes: BodyReader, RangeReader

Class Method Summary collapse

Methods included from HTTPChunkyReader

chunk_range_header, chunk_start

Methods included from ChunkyReader

#[], #chunk_size

Methods included from Reader

#fetch, open_with_uri, #stream, #unpack, #unpack1

Class Method Details

.open(uri) ⇒ Object



92
93
94
95
96
97
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/image_size/uri_reader.rb', line 92

def open(uri)
  http = nil
  (ImageSize.max_redirects + 1).times do
    ImageSize.uri_checker.call(uri)

    unless http && http.address == uri.host && http.port == uri.port
      http.finish if http

      http = Net::HTTP.new(uri.host, uri.port)
      http.use_ssl = true if uri.scheme == 'https'
      http.start
    end

    response = http.request_get(uri.request_uri, chunk_range_header(0)) do |response_with_unread_body|
      case response_with_unread_body
      when Net::HTTPOK
        return yield BodyReader.new(response_with_unread_body)
      end
    end

    case response
    when Net::HTTPRedirection
      uri += response['location']
    when Net::HTTPPartialContent
      m = response['content-range'].match(%r{\bbytes\s+\d+-\d+/(\d+)}i) if response['content-range']
      byte_size = m[1].to_i if m
      return yield RangeReader.new(http, uri.request_uri, response.body, byte_size)
    when Net::HTTPRequestedRangeNotSatisfiable
      return yield StringReader.new('')
    else
      fail "Unexpected response: #{response}"
    end
  end

  fail "Too many redirects: #{uri}"
ensure
  http.finish if http && http.started?
end