Fix current_page? when URL has trailing slash

This fixes the `current_page?` helper when the given URL has a trailing
slash, and is an absolute URL or also has query params.

Fixes #33956.

Co-authored-by: Rien Maertens <rien.maertens@posteo.be>
This commit is contained in:
Jonathan Hefner 2021-07-23 16:57:04 -05:00
parent fcacb93295
commit 8ace007519
2 changed files with 19 additions and 8 deletions

View File

@ -573,16 +573,14 @@ module ActionView
request_uri = url_string.index("?") || check_parameters ? request.fullpath : request.path
request_uri = URI::DEFAULT_PARSER.unescape(request_uri).force_encoding(Encoding::BINARY)
if url_string.start_with?("/") && url_string != "/"
url_string.chomp!("/")
request_uri.chomp!("/")
if %r{^\w+://}.match?(url_string)
request_uri = +"#{request.protocol}#{request.host_with_port}#{request_uri}"
end
if %r{^\w+://}.match?(url_string)
url_string == "#{request.protocol}#{request.host_with_port}#{request_uri}"
else
url_string == request_uri
end
remove_trailing_slash!(url_string)
remove_trailing_slash!(request_uri)
url_string == request_uri
end
if RUBY_VERSION.start_with?("2.7")
@ -802,6 +800,11 @@ module ActionView
params.sort_by { |pair| pair[:name] }
end
def remove_trailing_slash!(url_string)
trailing_index = (url_string.index("?") || 0) - 1
url_string[trailing_index] = "" if url_string[trailing_index] == "/"
end
end
end
end

View File

@ -625,6 +625,14 @@ class UrlHelperTest < ActiveSupport::TestCase
@request = request_for_url("/posts")
assert current_page?("/posts/")
assert current_page?("http://www.example.com/posts/")
end
def test_current_page_with_trailing_slash_and_params
@request = request_for_url("/posts?order=desc")
assert current_page?("/posts/?order=desc")
assert current_page?("http://www.example.com/posts/?order=desc")
end
def test_current_page_with_not_get_verb