JP Silvashy
JP Silvashy

Reputation: 48485

Rails: get params from a string

Say I have a string that is a url with params in it:

http://www.google.com/search?hl=en&client=firefox-a&hs=zlX&rls=org.mozilla%3Aen-US%3Aofficial&q=something&cts=1279154269301&aq=f&aqi=&aql=&oq=&gs_rfai=

How can can I form an array of all the params from the string? I'm aware of the params array that you can access but I'm talking about just any arbitrary string, not one part of the request.

Upvotes: 0

Views: 315

Answers (1)

Geoff Lanotte
Geoff Lanotte

Reputation: 7500

Not sure if there is a rails shortcut, but:

url = 'http://www.google.com/search?hl=en&client=firefox-a&hs=zlX&rls=org.mozilla%3Aen-US%3Aofficial&q=something&cts=1279154269301&aq=f&aqi=&aql=&oq=&gs_rfai='

params = CGI.parse(URI.parse(url).query)

#=> {"hs"=>["zlX"], "oq"=>[""], "cts"=>["1279154269301"], "aqi"=>[""], "rls"=>["org.mozilla:en-US:official"], "hl"=>["en"], "aq"=>["f"], "gs_rfai"=>[""], "aql"=>[""], "q"=>["something"], "client"=>["firefox-a"]}

params = CGI.parse(url) 

is almost there gives you:

#=> {"hs"=>["zlX"], "oq"=>[""], "cts"=>["1279154269301"], "aqi"=>[""], "rls"=>["org.mozilla:en-US:official"], "aq"=>["f"], "http://www.google.com/search?hl"=>["en"], "gs_rfai"=>[""], "aql"=>[""], "q"=>["something"], "client"=>["firefox-a"]}

Upvotes: 2

Related Questions