86

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, so I get a hash like this:

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

Or must I write it myself?

EDIT

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.

Julik
  • 7,676
  • 2
  • 34
  • 48

5 Answers5

176

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.

Julik
  • 7,676
  • 2
  • 34
  • 48
  • If you want to get a params object like rails provides for you, you can do this: params = ActionController::Parameters.new(Rack::Utils.parse_nested_query("a=2")) – adailey Mar 29 '17 at 16:21
  • Does anyone know whether it's possible to avoid having the query string param values cast to strings? e.g. I want this behavior: ``` Rack::Utils.raw_parse_nested_query("a=2") #=> {"a" => 2} ``` – mecampbellsoup Mar 30 '17 at 16:00
  • 1
    While this is nice most of the time: it parses `"a[]=&a[]=z"` as `{"a[]"=>["", "z"]}`, wheras whatever parser is actually used by `ActionController::Base` returns `{:a => ["z"]}` – Jeremy List Nov 27 '18 at 21:40
  • Doc: https://www.rubydoc.info/gems/rack/Rack%2FQueryParser:parse_nested_query – Ulysse BN May 17 '21 at 16:25
40

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.

dombesz
  • 7,890
  • 5
  • 38
  • 47
  • 2
    This is the only implementation I've tried that handles multiple instances of each param -- Thanks! – Ryan Long Jun 26 '12 at 20:58
  • 8
    Problem is that most people don't want arrays and are expecting a simple key=>value response – Ben G Sep 05 '13 at 23:45
  • @julik answer should be accepted. `CGI::parse` does not handles array correctly – Ben Jan 06 '22 at 17:01
15

Edit : as said in the comments, symolizing keys can bring your server down if someone want to hurt you. I still do it a lot when I work on low profile apps because it makes things easier to work with but I wouldn't do it anymore for high stake apps

Do not forget to symbolize the keys for obtaining the result you want

Rack::Utils.parse_nested_query("a=2&b=tralalala").deep_symbolize_keys

this operation is destructive for duplicates.

systho
  • 1,161
  • 7
  • 17
  • 8
    Symbolizing user-supplied keys is a bad idea. Symbols do not GC, so if someone spams your server with alot of bogus parameter keys it will exhaust the process memory at some point. – Julik Jun 30 '12 at 22:49
  • 6
    Ruby 2.2 will GC symbols now. – Lesleh Jan 18 '15 at 22:28
9

If you talking about the Urls that is being used to get data about the parameters them

> request.url
=> "http://localhost:3000/restaurants/lokesh-dhaba?data=some&more=thisIsMore"

Then to get the query parameters. use

> request.query_parameters
=> {"data"=>"some", "more"=>"thisIsMore"}
lokeshjain2008
  • 1,879
  • 1
  • 22
  • 36
2

If you want a hash you can use

Hash[CGI::parse(x).map{|k,v| [k, v.first]}]
Arnold Roa
  • 7,335
  • 5
  • 50
  • 69