DZone Snippets is a public source code repository. Easily build up your personal collection of code snippets, categorize them with tags / keywords, and share them with the world

Calvin has posted 1 posts at DZone. View Full User Profile

URI Encoding In Ruby

01.21.2006
| 78143 views |
  • submit to reddit
        To encode the web parameters for a URL query string.

require 'uri'
val = URI.escape("my parameter value")
    

Comments

Snippets Manager replied on Thu, 2008/04/10 - 5:48am

uri_good = URI.escape(foo, Regexp.new("[^#{URI::PATTERN::UNRESERVED}]")) cgi_good = CGI.escape(foo) puts uri_good == cgi_good # => true That's not really true. Try to put a space into url - URI escapes them as "%20", CGI escapes them as "+"

Snippets Manager replied on Wed, 2007/11/28 - 1:07pm

Or you can fully escape the URI using CGI: require 'uri' require 'cgi' foo = "http://google.com?query=hello" uri_good = URI.escape(foo, Regexp.new("[^#{URI::PATTERN::UNRESERVED}]")) cgi_good = CGI.escape(foo) puts uri_good == cgi_good # => true

Snippets Manager replied on Thu, 2006/10/05 - 6:41pm

To _fully_ escape a URI, you'll have to do this: require 'uri' val = URI.escape("abc&efg?hijk", Regexp.new("[^#{URI::PATTERN::UNRESERVED}]")) Otherwise if you are trying to escape a value that contains a URI, the URI value won't be cnoded. For example: require 'uri' foo = "http://google.com?query=hello" bad = URI.escape(foo) good = URI.escape(foo, Regexp.new("[^#{URI::PATTERN::UNRESERVED}]")) bad_uri = "http://mysite.com?service=#{bad}&bar=blah" good_uri = "http://mysite.com?service=#{good}&bar=blah" puts bad_uri # outputs "http://mysite.com?service=http://google.com?query=hello&bar=blah" puts good_uri # outputs "http://mysite.com?service=http%3A%2F%2Fgoogle.com%3Fquery%3Dhello&bar=blah"