Class: ImageSize::URIReader

Inherits:
Object
  • Object
show all
Includes:
ChunkyReader
Defined in:
lib/image_size/uri_reader.rb

Overview

:nodoc:

Instance Method Summary collapse

Methods included from ChunkyReader

#chunk_size

Methods included from Reader

#fetch, open_with_uri, #unpack, #unpack1

Constructor Details

#initialize(uri, redirects = 5) ⇒ URIReader

Returns a new instance of URIReader.



17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
# File 'lib/image_size/uri_reader.rb', line 17

def initialize(uri, redirects = 5)
  if !@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

  @request_uri = uri.request_uri
  response = request_chunk(0)

  case response
  when Net::HTTPRedirection
    raise "Too many redirects: #{response['location']}" unless redirects > 0

    initialize(uri + response['location'], redirects - 1)
  when Net::HTTPOK
    @body = response.body
  when Net::HTTPPartialContent
    @chunks = { 0 => response.body }
  else
    raise "Unexpected response: #{response}"
  end
end

Instance Method Details

#[](offset, length) ⇒ Object



42
43
44
45
46
47
48
# File 'lib/image_size/uri_reader.rb', line 42

def [](offset, length)
  if @body
    @body[offset, length]
  else
    super
  end
end

#chunk(i) ⇒ Object



50
51
52
53
54
55
56
57
58
59
60
61
62
# File 'lib/image_size/uri_reader.rb', line 50

def chunk(i)
  unless @chunks.key?(i)
    response = request_chunk(i)
    case response
    when Net::HTTPPartialContent
      @chunks[i] = response.body
    else
      raise "Unexpected response: #{response}"
    end
  end

  @chunks[i]
end