Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is the most elegant way in Ruby to remove a parameter from a URL?

Tags:

url

parsing

ruby

I would like to take out a parameter from a URL by its name without knowing which parameter it is, and reassemble the URL again.

I guess it is not that hard to write something on my own using CGI or URI, but I imagine such functionality exists already. Any suggestions?

In:

http://example.com/path?param1=one&param2=2&param3=something3

Out:

http://example.com/path?param2=2&param3=something3
like image 592
dimus Avatar asked Jan 27 '10 19:01

dimus


People also ask

What is the best way to pass urls as URL parameters?

Using &url='+encodeURIComponent(url); to pass a URL from browser to server will encode the url but when it is decoded at the server, the parameters of url are interpreted as seperate parameters and not as part of the single url parameter.

Can you hide URL parameters?

You cannot hide parameters. Even if you use the post method instead of the get method to remove parameters from the url. You can still see the passed parameters in the request message. The way to safely hide parameters is to encrypt them.


2 Answers

I prefer to use:

require 'addressable/uri'

uri = Addressable::URI.parse('http://example.com/path?param1=one&param2=2&param3=something3')

params = uri.query_values #=> {"param1"=>"one", "param2"=>"2", "param3"=>"something3"}
params.delete('param1') #=> "one"
uri.query_values = params #=> {"param2"=>"2", "param3"=>"something3"}

uri.to_s #=> "http://example.com/path?param2=2&param3=something3"
like image 83
the Tin Man Avatar answered Oct 11 '22 20:10

the Tin Man


Maybe a little off-topic, but for anyone who's attempting to do this in the context of a rails app you can simply do:

url_for(params.except(:name_of_param_to_delete))

N.B. Tested in rails v2.3.9.

like image 44
fractious Avatar answered Oct 11 '22 22:10

fractious