解析字符串,就好像它是Ruby on Rails中的查询字符串 [英] Parse a string as if it were a querystring in Ruby on Rails

查看:69
本文介绍了解析字符串,就好像它是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天全站免登陆