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

前端 未结 3 1738
忘掉有多难
忘掉有多难 2021-02-07 10:54

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         


        
相关标签:
3条回答
  • 2021-02-07 11:18
    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
    
    0 讨论(0)
  • 2021-02-07 11:18

    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
    
    0 讨论(0)
  • 2021-02-07 11:25

    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
    
    0 讨论(0)
提交回复
热议问题