Ruby, How to add a param to an URL that you don

2019-03-18 12:28发布

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&param=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.

Update

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&param=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&param=value#&tro&lo&lo", add_param("http://url.com?p1=v1&p2=v2#&tro&lo&lo", "param", "value"))
  end
end

标签: ruby url params
2条回答
Evening l夕情丶
2楼-- · 2019-03-18 13:09

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
查看更多
Rolldiameter
3楼-- · 2019-03-18 13:17
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&param=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
查看更多
登录 后发表回答