I have to add a new param to an indeterminate URL, let\'s say param=value
.
In case the actual URL has already params like this
http://url.co
require 'uri'
uri = URI("http://url.com?p1=v1&p2=2")
ar = URI.decode_www_form(uri.query) << ["param","value"]
uri.query = URI.encode_www_form(ar)
p uri #=> #<URI::HTTP:0xa0c44c8 URL:http://url.com?p1=v1&p2=2¶m=value>
uri = URI("http://url.com")
uri.query = "param=value" if uri.query.nil?
p uri #=> #<URI::HTTP:0xa0eaee8 URL:http://url.com?param=value>
EDIT:(by fguillen, to merge all the good propositions and also to make it compatible with his question test suite.)
require 'uri'
def add_param(url, param_name, param_value)
uri = URI(url)
params = URI.decode_www_form(uri.query || "") << [param_name, param_value]
uri.query = URI.encode_www_form(params)
uri.to_s
end
Well, you may also not know if this parameter already exists in url. If you want to replace it with new value in this case, you can do this:
url = 'http://example.com?exists=0&other=3'
params = {'exists' => 1, "not_exists" => 2}
uri = URI.parse url
uri.query = URI.encode_www_form(URI.decode_www_form(uri.query || '').to_h.merge(params))
uri.to_s
More elegant solution:
url = 'http://example.com?exiting=0'
params = {new_param: 1}
uri = URI.parse url
uri.query = URI.encode_www_form URI.decode_www_form(uri.query || '').concat(params.to_a)
uri.to_s #=> http://example.com?exiting=0&new_param=1