Ruby URI Percent Encoding
Written by Ben on March 30, 2007 |
CGI.escape and URI.escape are both available in the standard Ruby libraries for URL encoding. But which one should you use?
Here’s a quick note about the differences:
irb(main):001:0> require ‘cgi’
=> true
irb(main):002:0> require ‘uri’
=> true
irb(main):003:0> URI.escape(’Test Hi<>?/&;=:’)
=> “Test%20Hi%3C%3E?/&;=:”
irb(main):004:0> URI.escape(’Test Hi<>?/&;=:’, ‘&’)
=> “Test Hi<>?/%26;=:”
irb(main):005:0> CGI.escape(’Test Hi<>?/&;=:’)
=> “Test+Hi%3C%3E%3F%2F%26%3B%3D%3A”
Note that URI.escape fails to encode the ampersand… So definitely use CGI.escape if you want to safely encode a query parameter for net/http calls.
Posted in Ruby
![[del.icio.us]](http://badpopcorn.com/blog/wp-content/plugins/bookmarkify/delicious.png)
![[Digg]](http://badpopcorn.com/blog/wp-content/plugins/bookmarkify/digg.png)
![[Google]](http://badpopcorn.com/blog/wp-content/plugins/bookmarkify/google.png)
![[StumbleUpon]](http://badpopcorn.com/blog/wp-content/plugins/bookmarkify/stumbleupon.png)
![[Windows Live]](http://badpopcorn.com/blog/wp-content/plugins/bookmarkify/windowslive.png)
![[Yahoo!]](http://badpopcorn.com/blog/wp-content/plugins/bookmarkify/yahoo.png)
![[Email]](http://badpopcorn.com/blog/wp-content/plugins/bookmarkify/email.png)
Not only did URI not encode the ampersand but it neglected the /. I noticed this same issue with strings like “3/4″ in a url.
Comment by Phillip Novess — May 3, 2007 @ 8:39 pm