el_quick
el_quick

Reputation: 4746

Get URL string parameters?

I have this URL in my database, in the "location" field:

http://www.youtube.com/watch?v=xxxxxxxxxxxxxxxxxxx

I can get it with @object.location, but how can I get the value of v? I mean, get "xxxxxxxxxxxx" from the URL string?

Upvotes: 9

Views: 9147

Answers (3)

el_quick
el_quick

Reputation: 4746

$ irb

irb(main):001:0> require 'cgi' => true
irb(main):002:0> test = CGI::parse('v=xxxxxxxxxxxxxxxxxxx') => {"v"=>["xxxxxxxxxxxxxxxxxxx"]}
irb(main):003:0> puts test['v']
xxxxxxxxxxxxxxxxxxx
=> nil

Upvotes: 0

mikej
mikej

Reputation: 66263

require 'uri'
require 'cgi'

# use URI.parse to parse the URL into its constituent parts - host, port, query string..
uri = URI.parse(@object.location)
# then use CGI.parse to parse the query string into a hash of names and values
uri_params = CGI.parse(uri.query)

uri_params['v'] # => ["xxxxxxxxxxxxxxxxxxx"]

Note that the return from CGI.parse is a Hash of Strings to Arrays so that it can handle multiple values for the same parameter name. For your example you would want uri_params['v'][0].

Also note that the Hash returned by CGI.parse will return [] if the requested key is not found, therefore uri_params['v'][0] will return either the value or nil if the URL did not contain a v parameter.

Upvotes: 21

AboutRuby
AboutRuby

Reputation: 8116

Beyond using a library to parse the entire URL into protocol, hostname, path and parameters, you could use a simple regexp to extract the information. Note that the regexp is a quick and dirty solution, and it'll fail if there's anything at all different about the URL, like if it has another parameter after the v parameter.

url = 'http://www.youtube.com/watch?v=xxxxxxxxxxxxxxxxxxx'
video_id = url.match(/\?v=(.+)$/)[1]

You can go further with what you did by using URI::parse to get the query information.

url = 'http://www.youtube.com/watch?v=xxxxxxxxxxxxxxxxxxx'
video_id = CGI::parse(URI::parse(url).query)['v']

Upvotes: 0

Related Questions