Andrew Grimm
Andrew Grimm

Reputation: 81691

How do I parse the query portion of a URI in Ruby 1.8?

In Ruby 1.8, using the URI standard library, I can parse

http://au.easyroommate.com/content/common/listing_detail.aspx?code=H123456789012&from=L123456789012345

using URI.split to get

["http", nil, "au.easyroommate.com", nil, nil,
"/content/common/listing_detail.aspx", nil, 
"code=H123456789012&from=L123456789012345", nil]

But is it possible to get the H123456789012 bit from the query portion without using my own hackery (eg splitting by & and then getting the bit that matches /code.(.*)/ ?

Upvotes: 3

Views: 218

Answers (2)

Ryan Bigg
Ryan Bigg

Reputation: 107738

You could use Rack::Utils which has a method called parse_nested_query which you could pass in the query string from the URL:

Rack::Utils.parse_nested_query(uri.query_string)

This will then return a Hash object representing the query string allowing you to gain access to the code.

Upvotes: 3

Maurício Linhares
Maurício Linhares

Reputation: 40333

You're looking for the CGI::parse method

params = CGI::parse("query_string")
  # {"name1" => ["value1", "value2", ...],
  #  "name2" => ["value1", "value2", ...], ... }

Upvotes: 3

Related Questions