Ruby url encode

Posted in Uncategorized on Jan 20, 2013

In one of the projects I’m working on I’ve been seeing the following all over the codebase.

CGI.escape(plaintext).gsub(“+”, “%20”).gsub(“%7E”, “~”)

At first you wonder why are they replacing “+” with “%20”.
Then you realize what they really wanted to use was “URI.encode”.

When using “URI.encode” you don’t need to gsub “+” with “%20”.

URI.encode("hello world") #=> "hello%20world"
CGI.escape("hello world") #=> "hello+world"
CGI.escape("Hello~world") #=> "Hello%7Eworld"
URI.encode("Hello~world") #=> "Hello~world"

Comments are closed.

  • Recent Comments