Skip to content

Instantly share code, notes, and snippets.

@mferrier
Created October 6, 2009 16:07
Show Gist options
  • Save mferrier/203163 to your computer and use it in GitHub Desktop.
Save mferrier/203163 to your computer and use it in GitHub Desktop.
# Return the current path with its query parameters, merging the passed parameters over any existing ones
# Include an :exclude key to remove the named existing parameter keys before merging
#
# Examples:
#
# # From http://localhost:3000/ncaab
# current_path_with_merged_parameters(:offset => 1)
# => "/ncaab?offset=1"
#
# # From http://localhost:3000/ncaab?offset=1
# current_path_with_merged_parameters(:offset => 2, :conference => 'poop')
# => "/ncaab?offset=2&conference=poop"
#
# # From http://localhost:3000/ncaab?offset=2&conference=poop
# current_path_with_merged_parameters(:offset => 0, :exclude => 'conference')
# => "/ncaab?offset=0"
def current_path_with_merged_parameters(params = {})
params.stringify_keys!
exclusions = Array(params.delete('exclude'))
current_params = (exclusions.any? ? request.query_parameters.excluding(exclusions) : request.query_parameters)
(request.path + '?' + current_params.merge(params).to_param).chomp('?')
end
module ActionController
class AbstractRequest
def query_parameters_excluding(*keys)
params = query_parameters.dup
keys.flatten.each do |key|
params.delete(key)
end
params
end
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment