提取由ruby中的哈希组成的URL

时间:2014-11-05 21:58:43

标签: ruby

我有一个查询字符串,如下所示:

http://localhost:3000/events?appointment_practices%5B10%5D=Injury&appointment_practices%5B18%5D=Immigration&appointment_practices%5B8%5D=Bankruptcy

appointment_practices实际上是我在重定向期间插入查询字符串的哈希:

appointment_practices = practices.reduce({}) do |acc, practice|
    acc[practice.id] = practice.class.name
    acc
end
redirect_to events_path(appointment_practices: appointment_practices)

现在我要解析该查询字符串。当我尝试使用decode_www_form解析它时,它返回一个带有nil元素的数组:

[nil]

这是给我nil元素的代码:

@http_refer = @_env['HTTP_REFERER']
begin
  uri = URI.parse @http_refer
  practices = Hash[URI::decode_www_form(uri.query)].values_at('appointment_practices')
  puts "practices: #{practices}"
rescue StandardError
end

我正在尝试提取哈希值。例如,在appointment_practices%5B10%5D = Injury中,id为10且练习为Injury。

除正则表达式外还有哪些其他选项?

1 个答案:

答案 0 :(得分:1)

您可以使用Rack::Utils.parse_nested_query

require 'uri'
require 'rack'

uri = URI.parse('http://localhost:3000/events?appointment_practices%5B10%5D=Injury&appointment_practices%5B18%5D=Immigration&appointment_practices%5B8%5D=Bankruptcy')
Rack::Utils.parse_nested_query(uri.query)
#=> {"appointment_practices"=>{"10"=>"Injury", "18"=>"Immigration", "8"=>"Bankruptcy"}}