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
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 49 def follow_redirect(uri, steps = URI_REDIRECT_MAX_STEPS, cache = URI_REDIRECT_HTTP_CACHE) 50 unless uri.is_a?(::URI::HTTP) 51 uri = ::URI.parse(uri.to_s) 52 return unless uri.is_a?(::URI::HTTP) 53 end 54 55 req = cache[[uri.host, uri.port]] 56 req.use_ssl = uri.is_a?(::URI::HTTPS) 57 58 ctx = req.instance_variable_get(:@ssl_context) if req.use_ssl? 59 ctx.verify_mode ||= ::OpenSSL::SSL::VERIFY_NONE if ctx 60 61 res = yield req, uri.request_uri 62 return res unless res.is_a?(::Net::HTTPRedirection) 63 return nil unless steps > 0 64 65 follow_redirect(res['Location'], steps - 1, cache) { |*a| yield(*a) } 66 rescue ::SocketError, ::Errno::EHOSTUNREACH, ::Errno::ENOENT 67 end
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 Nuggets::URI::RedirectMixin#follow_redirect
for more information.
# File lib/nuggets/uri/redirect_mixin.rb 94 def get_redirect(uri, steps = URI_REDIRECT_MAX_STEPS) 95 res = follow_redirect(uri, steps) { |req, path| req.get(path) } 96 res && block_given? ? yield(res) : res 97 end
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 Nuggets::URI::RedirectMixin#follow_redirect
for more information.
# File lib/nuggets/uri/redirect_mixin.rb 79 def head_redirect(uri, steps = URI_REDIRECT_MAX_STEPS) 80 res = follow_redirect(uri, steps) { |req, path| req.head(path) } 81 res && block_given? ? yield(res) : res 82 end