Skip to content

Commit

Permalink
Add on_redirect callback. (#722)
Browse files Browse the repository at this point in the history
  • Loading branch information
benubois committed Nov 12, 2022
1 parent 6bf9115 commit 13ce3c2
Show file tree
Hide file tree
Showing 2 changed files with 30 additions and 2 deletions.
6 changes: 4 additions & 2 deletions lib/http/redirector.rb
Original file line number Diff line number Diff line change
Expand Up @@ -40,8 +40,9 @@ class EndlessRedirectError < TooManyRedirectsError; end
# @option opts [Boolean] :strict (true) redirector hops policy
# @option opts [#to_i] :max_hops (5) maximum allowed amount of hops
def initialize(opts = {})
@strict = opts.fetch(:strict, true)
@max_hops = opts.fetch(:max_hops, 5).to_i
@strict = opts.fetch(:strict, true)
@max_hops = opts.fetch(:max_hops, 5).to_i
@on_redirect = opts.fetch(:on_redirect, nil)
end

# Follows redirects until non-redirect response found
Expand All @@ -65,6 +66,7 @@ def perform(request, response)
unless cookie_jar.empty?
@request.headers.set(Headers::COOKIE, cookie_jar.cookies.map { |c| "#{c.name}=#{c.value}" }.join("; "))
end
@on_redirect.call @response, @request if @on_redirect.respond_to?(:call)
@response = yield @request
collect_cookies_from_response
end
Expand Down
26 changes: 26 additions & 0 deletions spec/lib/http/redirector_spec.rb
Original file line number Diff line number Diff line change
Expand Up @@ -148,6 +148,32 @@ def redirect_response(status, location, set_cookie = {})
expect(cookies["deleted"]).to eq nil
end

context "with on_redirect callback" do
let(:options) do
{
:on_redirect => proc do |response, location|
@redirect_response = response
@redirect_location = location
end
}
end

it "calls on_redirect" do
req = HTTP::Request.new :verb => :head, :uri => "http://example.com"
hops = [
redirect_response(301, "http://example.com/1"),
redirect_response(301, "http://example.com/2"),
simple_response(200, "foo")
]

redirector.perform(req, hops.shift) do |prev_req, _|
expect(@redirect_location.uri.to_s).to eq prev_req.uri.to_s
expect(@redirect_response.code).to eq 301
hops.shift
end
end
end

context "following 300 redirect" do
context "with strict mode" do
let(:options) { {:strict => true} }
Expand Down

0 comments on commit 13ce3c2

Please sign in to comment.