module Nuggets::URI::RedirectMixin

Constants

URI_REDIRECT_HTTP_CACHE

Cache for HTTP objects to reuse.

URI_REDIRECT_MAX_STEPS

Maximum number of redirects to follow.

Public Instance Methods

follow_redirect(uri[, steps]) { |req, path| ... } → aResponse or +nil+ click to toggle source

Performs any HTTP request on uri while following at most steps redirects. Accepts both strings and URI objects for uri. Defers to the given block to perform the actual request; yields the request object and the request URI string.

Returns the response object if successful, or nil if uri is not an HTTP URI, the redirect limit has been exceeded, or any connection error occurs.

# File lib/nuggets/uri/redirect_mixin.rb, line 49
def follow_redirect(uri, steps = URI_REDIRECT_MAX_STEPS, cache = URI_REDIRECT_HTTP_CACHE)
  unless uri.is_a?(::URI::HTTP)
    uri = ::URI.parse(uri.to_s)
    return unless uri.is_a?(::URI::HTTP)
  end

  req = cache[[uri.host, uri.port]]
  req.use_ssl = uri.is_a?(::URI::HTTPS)

  ctx = req.instance_variable_get(:@ssl_context) if req.use_ssl?
  ctx.verify_mode ||= ::OpenSSL::SSL::VERIFY_NONE if ctx

  res = yield req, uri.request_uri
  return res unless res.is_a?(::Net::HTTPRedirection)
  return nil unless steps > 0

  follow_redirect(res['Location'], steps - 1, cache) { |*a| yield(*a) }
rescue ::SocketError, ::Errno::EHOSTUNREACH, ::Errno::ENOENT
end
get_redirect(uri[, steps]) → aResponse or +nil+ click to toggle source
get_redirect(uri[, steps]) { |res| ... } → anObject or +nil+

Performs a GET request on uri while following at most steps redirects. If successful, yields the response to the given block and returns its return value, or the response itself if no block was given. Returns nil in case of failure.

See #follow_redirect for more information.

# File lib/nuggets/uri/redirect_mixin.rb, line 94
def get_redirect(uri, steps = URI_REDIRECT_MAX_STEPS)
  res = follow_redirect(uri, steps) { |req, path| req.get(path) }
  res && block_given? ? yield(res) : res
end
head_redirect(uri[, steps]) → aResponse or +nil+ click to toggle source
head_redirect(uri[, steps]) { |res| ... } → anObject or +nil+

Performs a HEAD request on uri while following at most steps redirects. If successful, yields the response to the given block and returns its return value, or the response itself if no block was given. Returns nil in case of failure.

See #follow_redirect for more information.

# File lib/nuggets/uri/redirect_mixin.rb, line 79
def head_redirect(uri, steps = URI_REDIRECT_MAX_STEPS)
  res = follow_redirect(uri, steps) { |req, path| req.head(path) }
  res && block_given? ? yield(res) : res
end