Never been to DZone Snippets before?

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 (See related posts)

To encode the web parameters for a URL query string.

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

Comments on this post

Gunark posts on Oct 05, 2006 at 18:54
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"



metavida posts on Nov 28, 2007 at 12:10
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
szimek posts on Apr 10, 2008 at 05:52
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 "+"

You need to create an account or log in to post comments to this site.


Click here to browse all 4852 code snippets

Related Posts