From ed5893ffcd5f4e5365bbffe2e8f120529e4d98ca Mon Sep 17 00:00:00 2001 From: Ben Hollis Date: Sun, 30 Dec 2012 16:27:33 -0800 Subject: [PATCH] Add a :query option to link_to to allow specifying query string --- middleman-more/features/helpers_link_to.feature | 12 ++++++++++++ .../core_extensions/default_helpers.rb | 14 ++++++++++++++ 2 files changed, 26 insertions(+) diff --git a/middleman-more/features/helpers_link_to.feature b/middleman-more/features/helpers_link_to.feature index 3ecc0895..1607cc24 100644 --- a/middleman-more/features/helpers_link_to.feature +++ b/middleman-more/features/helpers_link_to.feature @@ -104,3 +104,15 @@ Feature: link_to helper Then I should see 'Needs Index Anchor' Then I should see 'Needs Index Query' Then I should see 'Needs Index Query and Anchor' + + Scenario: link_to accepts a :query option that appends a query string + Given a fixture app "indexable-app" + And a file named "source/link_to.html.erb" with: + """ + <%= link_to "Needs Index String", "/needs_index.html", :query => "foo" %> + <%= link_to "Needs Index Hash", "/needs_index.html", :query => { :foo => :bar } %> + """ + And the Server is running at "indexable-app" + When I go to "/link_to/" + Then I should see 'Needs Index String' + Then I should see 'Needs Index Hash' 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 dec9db17..1b2390f6 100644 --- a/middleman-more/lib/middleman-more/core_extensions/default_helpers.rb +++ b/middleman-more/lib/middleman-more/core_extensions/default_helpers.rb @@ -1,3 +1,5 @@ +require 'active_support/core_ext/object/to_query' + module Middleman module CoreExtensions # Built-in helpers @@ -113,6 +115,10 @@ module Middleman # set :relative_links, true # # to config.rb to have all links default to relative. + # + # There is also a :query option that can be used to append a + # query string, which can be expressed as either a String, + # or a Hash which will be turned into URL parameters. def link_to(*args, &block) url_arg_index = block_given? ? 0 : 1 options_index = block_given? ? 1 : 2 @@ -172,6 +178,14 @@ module Middleman end end + # Support a :query option that can be a string or hash + query = options.delete(:query) + if query + uri = URI(args[url_arg_index]) + uri.query = query.respond_to?(:to_param) ? query.to_param : query.to_s + args[url_arg_index] = uri.to_s + end + super(*args, &block) end end