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
URI Encoding In Ruby
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 # => trueThat'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
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 # => trueSnippets Manager replied on Thu, 2006/10/05 - 6:41pm
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"