Ruby,如何将参数添加到您不知道是否已具有其他参数的URL [英] Ruby, How to add a param to an URL that you don't know if it has any other param already

查看:60
本文介绍了Ruby,如何将参数添加到您不知道是否已具有其他参数的URL的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我必须在不确定的URL中添加一个新参数,例如param=value.

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

我应该将URL转换为另一个:

I should transform the URL to this other:

http://url.com?p1=v1&p2=v2&param=value

但是,如果URL还没有这样的参数:

But if the URL has not any param yet like this:

http://url.com

我应该将URL转换为另一个:

I should transform the URL to this other:

http://url.com?param=value

我很担心用Regex解决这个问题,因为我不确定寻找&是否足够.我在想,也许应该将URL转换为

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

推荐答案

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>

(由fguillen撰写,以合并所有好的建议,并使其与他的问题测试套件兼容.)

(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

这篇关于Ruby,如何将参数添加到您不知道是否已具有其他参数的URL的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆