是否有基于一组参数生成URL的Ruby库/ gem?

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)

  • 替换`Hash#to_query`:`URI.encode_www_form` (4认同)
  • 这只适用于使用rails的情况.如果你不使用rails,还有其他选择吗? (3认同)
  • @StefanHendriks事实并非如此:URI模块是一个标准的ruby库 - 它不需要Rails.在使用本答案中的代码之前,您必须发出"require"uri'`.否则它就像宣传的那样工作. (3认同)
  • `#Hash的'undefined方法'to_query':0x1c943d0>(NoMethodError) (2认同)

小智 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)