如何在Ruby中使用哈希值构建包含查询参数的URI

17

如何通过传递哈希来构造带有查询参数的URI对象?

我可以使用以下代码生成查询语句:

URI::HTTPS.build(host: 'example.com', query: "a=#{hash[:a]}, b=#{[hash:b]}")

它将生成:

https://example.com?a=argument1&b=argument2

然而,我认为对于许多参数来说,构建查询字符串会变得难以阅读和维护。我想通过传递哈希值来构建查询字符串。例如下面的示例:

hash = {
  a: 'argument1',
  b: 'argument2'
  #... dozen more arguments
}
URI::HTTPS.build(host: 'example.com', query: hash)

提高了

NoMethodError: undefined method `to_str' for {:a=>"argument1", :b=>"argument2"}:Hash

是否可以使用URI API基于哈希构造查询字符串?我不想对哈希对象进行猴子补丁操作...

2个回答

25
如果您已经安装了ActiveSupport,只需在哈希上调用'#to_query'即可。
hash = {
  a: 'argument1',
  b: 'argument2'
  #... dozen more arguments
}
URI::HTTPS.build(host: 'example.com', query: hash.to_query)

=> https://example.com?a=argument1&b=argument2

如果您没有使用Rails,请记得require 'uri'


14
to_query 是 Rails 中的一个方法,在 Ruby 中并不存在。 - marc_ferna
1
@marc_ferna的问题带有Ruby on Rails标签。你可以在非Rails项目中包含: ActiveSupport。 - Filip Bartuzi

25

对于不使用Rails或Active Support的人,解决方案是使用Ruby标准库:

hash = {
  a: 'argument1',
  b: 'argument2'
}
URI::HTTPS.build(host: 'example.com', query: URI.encode_www_form(hash))
=> #<URI::HTTPS https://example.com?a=argument1&b=argument2>

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接