像 Ruby on Rails 中的查询字符串一样解析字符串 [英] Parse a string as if it were a querystring in Ruby on Rails

查看:36
本文介绍了像 Ruby on Rails 中的查询字符串一样解析字符串的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个这样的字符串:

I have a string like this:

"foo=bar&bar=foo&hello=hi"

Ruby on Rails 是否提供了将其解析为查询字符串的方法,因此我得到这样的散列:

Does Ruby on Rails provide methods to parse this as if it is a querystring, so I get a hash like this:

{
    :foo => "bar",
    :bar => "foo",
    :hello => "hi"
}

还是我必须自己写?

请注意,上面的字符串不是来自 URL 的真正查询字符串,而是存储在 Facebook Connect cookie 中的字符串.

Please note that the string above is not a real querystring from a URL, but rather a string stored in a cookie from Facebook Connect.

推荐答案

答案取决于您使用的 Rails 版本.如果您使用的是 2.3 或更高版本,请使用 Rack 的内置解析器来解析参数

The answer depends on the version of Rails that you are using. If you are using 2.3 or later, use Rack's builtin parser for params

 Rack::Utils.parse_nested_query("a=2") #=> {"a" => "2"}

如果您使用的是较旧的 Rails,您确实可以使用 CGI::parse.请注意,散列和数组的处理在模块之间存在细微的差异,因此您需要验证您获得的数据对于您选择的方法是否正确.

If you are on older Rails, you can indeed use CGI::parse. Note that handling of hashes and arrays differs in subtle ways between modules so you need to verify whether the data you are getting is correct for the method you choose.

您还可以将 Rack::Utils 包含到您的类中以进行速记访问.

You can also include Rack::Utils into your class for shorthand access.

这篇关于像 Ruby on Rails 中的查询字符串一样解析字符串的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆