manuels manuels - 11 days ago 5
Ruby Question

Add parameter to url

I have a url (e.g. http://www.youtube.com/watch?v=og9B3BEnBHo) and I'd like to add a parameter to it (wmode=opaque) so that its:

http://www.youtube.com/watch?v=og9B3BEnBHo&wmode=opaque

Can anyone tell me which function to use to make this work?

Answer
require 'uri'

uri =  URI.parse("http://www.youtube.com/watch?v=og9B3BEnBHo")
uri.query = [uri.query, "wmode=opaque"].compact.join('&') 
puts uri.to_s

#edit Since 1.9.2 there are methods added to the URI module

uri =  URI.parse("http://www.youtube.com/watch?v=og9B3BEnBHo")
new_query_ar = URI.decode_www_form(String(uri.query)) << ["wmode", "opaque"]
uri.query = URI.encode_www_form(new_query_ar)
puts uri.to_s

(The call to String ensures that this also works in the case when the original URI does not have a query string)