class Addressable::URI

Public Instance Methods

fetch(limit: 50, use_get: :never) click to toggle source
# File lib/addressable/uri/fetch.rb, line 7
def fetch(limit: 50, use_get: :never)
  Net::HTTP.start(hostname, port, use_ssl: scheme == 'https') do |http|
    case use_get
    when :always
      response, uri = follow(http, self, limit, :get)
    when :never
      response, uri = follow(http, self, limit, :head)
    when :on_error
      response, uri = follow(http, self, limit, :head)
      response, uri = follow(http, self, (limit / 10).to_i, :get) unless response.is_a?(Net::HTTPOK)
    when :on_text
      response, uri = follow(http, self, limit, :head)
      response, uri = follow(http, self, (limit / 10).to_i, :get) if !response.is_a?(Net::HTTPOK) || text?(response.content_type)
    end

    response.uri ||= uri
    response
  end
end
fixup!() click to toggle source
# File lib/addressable/uri/fetch.rb, line 27
def fixup!
  normalize!
end

Private Instance Methods

follow(http, uri, limit, method) click to toggle source
# File lib/addressable/uri/fetch.rb, line 37
def follow(http, uri, limit, method)
  limit.times do
    request = case method
              when :get
                Net::HTTP::Get.new(uri)
              when :head
                Net::HTTP::Head.new(uri)
              end
    request['user-agent'] = 'Mozilla/5.0'

    response = http.request(request)

    return response, uri unless response.is_a?(Net::HTTPRedirection)

    previous_uri = uri
    uri = self.class.join(uri, response['location']).fixup!

    # Detect redirect loops
    return response, uri if uri == previous_uri
  end
end
text?(type) click to toggle source
# File lib/addressable/uri/fetch.rb, line 33
def text?(type)
  type == 'application/json' || type.start_with?('text/')
end