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

前端 未结 3 1740
忘掉有多难
忘掉有多难 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 = URI("http://url.com")
    uri.query = "param=value" if uri.query.nil?
    p uri #=> #
    

    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
    

提交回复
热议问题