9

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?

the Tin Man
  • 158,662
  • 42
  • 215
  • 303
SimonMayer
  • 4,719
  • 4
  • 33
  • 45
  • You might want to look at the [Addressable](http://addressable.rubyforge.org/api/) gem. It's everything Ruby's URI is, and a lot more. Highly recommended for anything beyond simple URL manipulation. – the Tin Man Feb 09 '12 at 19:27

2 Answers2

11

URI.encode_www_form works well and is more convenient for adding multiple arguments

q = URI.encode_www_form("show" => "Rosie & Jim", "series" => "3", "episode" => "4")
u = URI::HTTP.new("http", nil, "mydomain.example", nil, nil, "/tv/ragdoll", nil, q, nil)
SimonMayer
  • 4,719
  • 4
  • 33
  • 45
10

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

Baldrick
  • 23,882
  • 6
  • 74
  • 79
  • Thanks. That does the job. I noticed that spaces show as pluses; so when I looked that up, I found the encoding in URL queries is called "www_form"; this led me to find a more convenient way to do it with open-uri, but I accept your answer because it does exactly what I asked for. – SimonMayer Feb 09 '12 at 17:08