Parse a string as if it were a querystring in Ruby on Rails

前端 未结 5 401
终归单人心
终归单人心 2020-11-28 23:12

I have a string like this:

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

Does Ruby on Rails provide methods to parse this as if it is a querystring,

5条回答
  •  轻奢々
    轻奢々 (楼主)
    2020-11-28 23:52

    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"}
    

    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.

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

提交回复
热议问题