From 8ace007519d04fa1afc16340a4ee1d2b56a62cb6 Mon Sep 17 00:00:00 2001 From: Jonathan Hefner Date: Fri, 23 Jul 2021 16:57:04 -0500 Subject: [PATCH] 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 --- .../lib/action_view/helpers/url_helper.rb | 19 +++++++++++-------- actionview/test/template/url_helper_test.rb | 8 ++++++++ 2 files changed, 19 insertions(+), 8 deletions(-) diff --git a/actionview/lib/action_view/helpers/url_helper.rb b/actionview/lib/action_view/helpers/url_helper.rb index f09502937b..849e1f9b71 100644 --- a/actionview/lib/action_view/helpers/url_helper.rb +++ b/actionview/lib/action_view/helpers/url_helper.rb @@ -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 diff --git a/actionview/test/template/url_helper_test.rb b/actionview/test/template/url_helper_test.rb index 16dad5f70b..6cd54fc40b 100644 --- a/actionview/test/template/url_helper_test.rb +++ b/actionview/test/template/url_helper_test.rb @@ -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