How do I add encoded query values to a URL?

SimonMayer picture SimonMayer · Feb 9, 2012 · Viewed 9k times · Source

I am looking for a convenient and functional way to add encoded values to a URL query string in Ruby. Currently, I have:

require 'open-uri'

u = URI::HTTP.new("http", nil, "mydomain.example", nil, nil, "/tv", nil, "show=" + URI::encode("Rosie & Jim"), nil) 

p u.to_s # => "http://mydomain.example/tv?show=Rosie%20&%20Jim"

This isn't what I'm looking for, because I need to get "http://mydomain.example/tv?show=Rosie%20%26%20Jim", so that the show= value is not truncated.

Does Open::URI have another method that would do this? If not, can it be done with any other standard Ruby, or gem?

Answer

Baldrick picture Baldrick · Feb 9, 2012

Try with CGI::escape instead of URI::encode . doc here