Ste*_*ven 23 ruby gem ruby-on-rails
Rails的URL生成机制(大多数polymorphic_url
在某些时候路由)允许将至少为GET请求序列化的哈希传递到查询字符串中.获得这种功能的最佳方法是什么,但是在任何基本路径之上?
例如,我想要有以下内容:
generate_url('http://www.google.com/', :q => 'hello world')
# => 'http://www.google.com/?q=hello+world'
Run Code Online (Sandbox Code Playgroud)
我当然可以编写自己的,完全符合我的应用程序的要求,但如果存在一些规范库来处理它,我宁愿使用它:).
d11*_*wtq 38
是的,在Ruby的标准库中,您将找到用于处理URI的整个类模块.有一个用于HTTP.您可以#build
使用一些参数调用,就像您展示的那样.
http://www.ruby-doc.org/stdlib/libdoc/uri/rdoc/classes/URI/HTTP.html#M009497
对于查询字符串本身,只需使用Rails的哈希添加#to_query
.即
uri = URI::HTTP.build(:host => "www.google.com", :query => { :q => "test" }.to_query)
Run Code Online (Sandbox Code Playgroud)
小智 7
Late to the party, but let me highly recommend the Addressable gem. In addition to its other useful features, it supports writing and parsing uri's via RFC 6570 URI templates. To adapt the given example, try:
gsearch = Addressable::Template.new('http://google.com/{?query*}')
gsearch.expand(query: {:q => 'hello world'}).to_s
# => "http://www.google.com/?q=hello%20world"
Run Code Online (Sandbox Code Playgroud)
or
gsearch = Addressable::Template.new('http://www.google.com/{?q}')
gsearch.expand(:q => 'hello world').to_s
# => "http://www.google.com/?q=hello%20world"
Run Code Online (Sandbox Code Playgroud)
归档时间: |
|
查看次数: |
13237 次 |
最近记录: |