【问题标题】:How to construct URI with query arguments from hash in Ruby如何在Ruby中使用来自哈希的查询参数构造URI
【发布时间】:2016-01-20 07:53:59
【问题描述】:

如何通过传递哈希来构造带有查询参数的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 基于哈希构造查询字符串?我不想修补哈希对象...

【问题讨论】:

    标签: ruby-on-rails ruby hash uri ruby-2.2


    【解决方案1】:

    对于那些不使用 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>
    

    【讨论】:

      【解决方案2】:

      如果您有 ActiveSupport,只需在哈希上调用 '#to_query'

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

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

      如果你不使用 Rails,记得require 'uri'

      【讨论】:

      • to_query 是 Rails 唯一的方法。它在 Ruby 中不存在。
      • @marc_ferna questions 有 ruby​​ on rails 标签。您可以包括:非 Rails 项目中的 ActiveSupport
      猜你喜欢
      • 1970-01-01
      • 2013-01-19
      • 2013-04-28
      • 1970-01-01
      • 2013-05-10
      • 2016-05-10
      • 1970-01-01
      • 1970-01-01
      • 2011-02-27
      相关资源
      最近更新 更多