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

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.


The

CGI::parse("foo=bar&bar=foo&hello=hi")

Gives you

{"foo"=>["bar"], "hello"=>["hi"], "bar"=>["foo"]}

Edit: As specified by Ryan Long this version accounts for multiple values of the same key, which is useful if you want to parse arrays too.

Edit 2:

As Ben points out, this may not handle arrays well when they are formatted with ruby on rails style array notation. The rails style array notation is: foo[]=bar&foo[]=nop. That style is indeed handled correctly with Julik's response.

This version will only parse arrays correctly, if you have the params like foo=bar&foo=nop.