views:

867

answers:

4

Hi,

I have some URLs, like http://www.example.com/something?param1=value1&param2=value2&param3=value3, and I would like to extract the parameters from these URLs and get them in a Hash. Obviously, I could use regular expressions, but I was just wondering if there was easier ways to do that with Ruby or Rails. I haven't found anything in the Ruby Module 'URI' but perhaps I missed something.

In fact, I need a method that would do that :

extract_parameters_from_url("http://www.example.com/something?param1=value1&param2=value2&param3=value3")
=> {:param1 => 'value1', :param2 => 'value2', :param3 => 'value3'}

Would you have some advices? Thanks in advance.

Julien

+1  A: 

In your Controller, you should be able to access a dictionary (hash) called params. So, if you know what the names of each query parameter is, then just do params[:param1] to access it... If you don't know what the names of the parameters are, you could traverse the dictionary and get the keys.

Some simple examples here.

kchau
OK, I knew that, it works well in the controller with the requested URL, but how to do that for others arbitrary URLs?
Flackou
+2  A: 

I think you want to turn any given URL string into a HASH?

you can try http://www.ruby-doc.org/stdlib/libdoc/cgi/rdoc/classes/CGI.html#M000075

require 'cgi'

CGI::parse('param1=value1&param2=value2&param3=value3')

returns

{"param1"=>["value1"], "param2"=>["value2"], "param3"=>["value3"]}

Sniper
Flackou
For clarity, @Flackou wants this: `CGI.parse(URI.parse(url).query)`
glenn jackman
I haven't tested this, but the first key listed, containing the full url, seems really wrong.
Levi
+4  A: 

Rack is great at this. Here's how I'd tackle it:

require 'rack'
uri = 'http://www.example.com/something?param1=value1&param2=value2&param3=value3'
env = Rack::MockRequest.env_for(uri)
req = Rack::Request.new(env)
req.params  # => {"param1"=>"value1", "param2"=>"value2", "param3"=>"value3"}
Levi
thanks, dude. this is exactly what i was looking for.
Attila Györffy
+1  A: 

I found myself needing the same thing for a recent project. Building on Levi's solution, here's a cleaner and faster method:

Rack::Utils.parse_nested_query 'param1=value1&param2=value2&param3=value3'
# => {"param1"=>"value1", "param2"=>"value2", "param3"=>"value3"}
Arthur Gunn