我在字符串中有一个URL。添加一些参数的最简洁方法是什么?
e.g。
base = 'http://example.com'
uri1 = some_magical_method(base, :p1 => 'v1') # => http://example.com/?p1=v1
uri2 = some_magical_method(uri1, :p2 => 'v2') # => http://example.com/?p1=v1&p2=v2
uri3 = some_magical_method(uri2, :p3 => nil) # => http://example.com/?p1=v1&p2=v2
1)在Ruby?
2)在Rails中?
答案 0 :(得分:16)
在Rails中,ActiveSupport可用,最简单的方法是构造一个哈希,然后在其上调用#to_query
。
>> params = {}
>> params[:foo] = "bar"
>> params[:baz] = "bang"
>> params.to_query
=> "baz=bang&foo=bar"
在纯Ruby中,同样适用,但您需要自己编写编码器:
require 'cgi'
def to_query(hsh)
hsh.map {|k, v| "#{k}=#{CGI::escape v}" }.join("&")
end
params = {}
params[:foo] = "bar"
params[:baz] = "bang"
to_query params
=> "baz=bang&foo=bar"
答案 1 :(得分:5)
require 'open-uri'
def params_to_query(params)
params.map {|p, v| "#{p}=#{URI.escape(v.to_s)}"}.join('&')
end
def append_url(url, params = {})
uri = URI.parse(url)
uri.query = uri.query.nil? ? params_to_query(params) : [uri.query, params_to_query(params)].join('&') unless params.empty?
uri.to_s
end
puts append_url('http://example.com', {:query => 'my_example'} # "http://example.com?query=my_example"