Ruby, How to add a param to an URL that you don't know if it has any other param already

拥有回忆 提交于 2019-12-04 10:32:18

问题


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

回答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&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



回答2:


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


来源:https://stackoverflow.com/questions/16623421/ruby-how-to-add-a-param-to-an-url-that-you-dont-know-if-it-has-any-other-param

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!