ruby-on-rails – 在Ruby on Rails中逐步构建任意URL

前端之家收集整理的这篇文章主要介绍了ruby-on-rails – 在Ruby on Rails中逐步构建任意URL前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
我在字符串中有一个URL.添加一些参数的最简洁方法是什么?

例如

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中?

解决方法

在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"
原文链接:https://www.f2er.com/ruby/271312.html

猜你在找的Ruby相关文章