URL Escape and URL Unescape
I find these functions really handy when having to escape or unescape URL:
def url_escape(string)
string.gsub(/([^ a-zA-Z0-9_.-]+)/n) do
'%' + $1.unpack('H2' * $1.size).join('%').upcase
end.tr(' ', '+')
end
def url_unescape(string)
string.tr('+', ' ').gsub(/((?:%[0-9a-fA-F]{2})+)/n) do
[$1.delete('%')].pack('H*')
end
end
I usually place them in application.rb.
7 Comments:
Alternatively, you can use the functions from the CGI module, CGI.escape and CGI.unescape. You can invoke these directly, since they're already require'd in the framework.
What about the regular URI Ruby object, as described in "URI Encoding in Ruby"... seems even simpler to me!
[1] http://www.ruby-doc.org/core/classes/URI/Escape.html
[2] http://www.bigbold.com/snippets/posts/show/1260
I had problems using CGI.escape as it doesn't escape dots which was breaking my routing. These little regexes with a couple of minor modifications did the trick for me.
If you want you can try:
URI.escape(CGI.escape(url),'.')
This will encode the dot too. Def more complicated than it needs to be though.
This comment has been removed by the author.
http://snippets.dzone.com/posts/show/1260 shows how to really get it
Post a Comment
<< Home