From 3214cac153166c3baaca153f1ed2241d917b8424 Mon Sep 17 00:00:00 2001 From: Ben Hollis Date: Fri, 21 Dec 2012 18:25:49 -0800 Subject: [PATCH] Make link_to ignore (and preserve) query string and anchor in URLs/paths. --- middleman-more/features/helpers_link_to.feature | 13 +++++++++++++ .../core_extensions/default_helpers.rb | 12 ++++++++---- 2 files changed, 21 insertions(+), 4 deletions(-) diff --git a/middleman-more/features/helpers_link_to.feature b/middleman-more/features/helpers_link_to.feature index 990e7e8a..3ecc0895 100644 --- a/middleman-more/features/helpers_link_to.feature +++ b/middleman-more/features/helpers_link_to.feature @@ -91,3 +91,16 @@ Feature: link_to helper When I go to "/link_to.html" Then I should see 'Needs Index' + Scenario: link_to preserves query string and anchor and isn't messed up by them + Given a fixture app "indexable-app" + And a file named "source/link_to.html.erb" with: + """ + <%= link_to "Needs Index Anchor", "/needs_index.html#foo" %> + <%= link_to "Needs Index Query", "/needs_index.html?foo" %> + <%= link_to "Needs Index Query and Anchor", "/needs_index.html?foo#foo" %> + """ + And the Server is running at "indexable-app" + When I go to "/link_to/" + Then I should see 'Needs Index Anchor' + Then I should see 'Needs Index Query' + Then I should see 'Needs Index Query and Anchor' diff --git a/middleman-more/lib/middleman-more/core_extensions/default_helpers.rb b/middleman-more/lib/middleman-more/core_extensions/default_helpers.rb index b9b5076e..8da2072a 100644 --- a/middleman-more/lib/middleman-more/core_extensions/default_helpers.rb +++ b/middleman-more/lib/middleman-more/core_extensions/default_helpers.rb @@ -130,11 +130,13 @@ module Middleman # Handle relative urls current_source_dir = Pathname('/' + current_resource.path).dirname - path = Pathname(url) + uri = URI(url) + url_path = uri.path - url = current_source_dir.join(path).to_s if path.relative? + path = Pathname(url_path) + url_path = current_source_dir.join(path).to_s if path.relative? - resource = sitemap.find_resource_by_path(url) + resource = sitemap.find_resource_by_path(url_path) # Allow people to turn on relative paths for all links with set :relative_links, true # but still override on a case by case basis with the :relative parameter. @@ -159,7 +161,9 @@ module Middleman new_url = resource.url end - args[url_arg_index] = new_url + uri.path = new_url + + args[url_arg_index] = uri.to_s else raise "No resource exists at #{url}" if relative end