When dealing with URLs and HTML code, you must be careful to quote
certain characters. For instance, a slash character (``/'') has
special meaning in a URL, so it must be ``escaped'' if it's not part
of the path name. That is, any ``/'' in the query portion of the URL
will be translated to the string ``
%2F
'' and must be translated back
to a ``/'' for you to use it. Space and ampersand are also special
characters. To handle this,
CGI
provides the routines
CGI.escape
and
CGI.unescape
:
require 'cgi'
puts CGI.escape( "Nicholas Payton/Trumpet & Flugel Horn" )
|
produces:
Nicholas+Payton%2FTrumpet+%26+Flugel+Horn
|
Similarly, you may want to escape HTML special characters:
require 'cgi'
puts CGI.escapeHTML( '<a href="/mp3">Click Here</a>' )
|
produces:
<a href="/mp3">Click Here</a>
|
To get really fancy, you can decide to escape only certain elements
within a string:
require 'cgi'
puts CGI.escapeElement('<hr><a href="/mp3">Click Here</a><br>','A')
|
produces:
<hr><a href="/mp3">Click Here</a><br>
|
Here only the ``
A
'' tag is escaped; other tags are left alone.
Each of these methods has an ``
un
-'' version to restore the original
string.