Ruby url encode
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”.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
URI.encode("hello world") #=> "hello%20world" | |
CGI.escape("hello world") #=> "hello+world" | |
CGI.escape("Hello~world") #=> "Hello%7Eworld" | |
URI.encode("Hello~world") #=> "Hello~world" |