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.com?p1=v1&p2=v2
I should transform the URL to this other:
http://url.com?p1=v1&p2=v2¶m=value
But if the URL has not any param yet like this:
http://url.com
I should transform the URL to this other:
http://url.com?param=value
I feel worry to solve this with Regex because I'm not sure that looking for the presence of &
could be enough. I'm thinking that maybe I should transform the URL to an URI object, and then add the param and transform it to String again.
Looking for any suggestion from someone who has been already in this situation.
To help with the participation I'm sharing a basic test suite:
require "minitest"
require "minitest/autorun"
def add_param(url, param_name, param_value)
# the code here
"not implemented"
end
class AddParamTest < Minitest::Test
def test_add_param
assert_equal("http://url.com?param=value", add_param("http://url.com", "param", "value"))
assert_equal("http://url.com?p1=v1&p2=v2¶m=value", add_param("http://url.com?p1=v1&p2=v2", "param", "value"))
assert_equal("http://url.com?param=value#&tro&lo&lo", add_param("http://url.com#&tro&lo&lo", "param", "value"))
assert_equal("http://url.com?p1=v1&p2=v2¶m=value#&tro&lo&lo", add_param("http://url.com?p1=v1&p2=v2#&tro&lo&lo", "param", "value"))
end
end
Query parameters are a defined set of parameters attached to the end of a url. They are extensions of the URL that are used to help define specific content or actions based on the data being passed. To append query params to the end of a URL, a '? ' Is added followed immediately by a query parameter.
To add a parameter to the URL, add a /#/? to the end, followed by the parameter name, an equal sign (=), and the value of the parameter. You can add multiple parameters by including an ampersand (&) between each one.
To check if a url has query parameters, call the indexOf() method on the url, passing it a question mark, and check if the result is not equal to -1 , e.g. url. indexOf('? ') !== -1 .
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With