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

I have a line like this:

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

Does Ruby on Rails provide methods for parsing this as if it were a request, so I get a hash like this:

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

Or should I write myself?

EDIT

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

+51
query-string ruby-on-rails parsing
May 05 '10 at 11:38
source share
4 answers

The answer depends on the version of Rails you are using. If you are using 2.3 or later, use the built-in Rack parser for parameters

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

If you are on old Rails, you can really use CGI::parse . Please note that the handling of hashes and arrays differs subtlely between modules, so you need to check whether the data you receive is correct for the method you choose.

You can also include Rack::Utils in your class for reduced access.

+122
May 05 '10 at 16:34
source share

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

Gives you

 {"foo"=>["bar"], "hello"=>["hi"], "bar"=>["foo"]} 
+27
May 05 '10 at 12:17
source share

Edit: as said in the comments, symolizing keys can bring your server down if someone wants to harm you. I still do a lot when I work in low-profile applications, because it simplifies the work, but I would no longer do this for high-rate applications.

Do not forget to symbolize the keys to get the desired result.

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

this operation is destructive for duplicates.

+8
Feb 02 2018-12-12T00:
source share

If you are talking about Urls, which is used to get parameter data, they

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

Then, to get the request parameters. use

 > request.query_parameters => {"data"=>"some", "more"=>"thisIsMore"} 
+8
02 Oct '14 at 5:20
source share



All Articles