Saturday, July 29, 2006

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:

At 9:06 PM, Anonymous Anonymous said...

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.

 
At 11:46 AM, Anonymous Anonymous said...

What about the regular URI Ruby object, as described in "URI Encoding in Ruby"... seems even simpler to me!

 
At 11:50 AM, Anonymous Anonymous said...

[1] http://www.ruby-doc.org/core/classes/URI/Escape.html
[2] http://www.bigbold.com/snippets/posts/show/1260

 
At 7:53 AM, Blogger superluminary said...

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.

 
At 3:56 PM, Blogger Brian Armstrong said...

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.

 
At 6:15 PM, Blogger Roger Pack said...

This comment has been removed by the author.

 
At 6:34 PM, Blogger Roger Pack said...

http://snippets.dzone.com/posts/show/1260 shows how to really get it

 

Post a Comment

<< Home

eXTReMe Tracker