55997cec217233703cbf68b689578771

I'm looking for an easier/better way to to have the code property html encoded. Any way for this to be shorter and less ugly?

def encode
    self[:code] = self[:code].gsub(/\&/, "&amp;").gsub(/\</, "&lt;").gsub(/\>/, "&gt;")
end

Refactorings

No refactoring yet !

73415a883aec7c0a7aada9c4cdb208b5

Christoffer

February 14, 2010, February 14, 2010 08:27, permalink

No rating. Login to rate!

There is a library for what you want to do at:
http://htmlentities.rubyforge.org/

Your solution is simple but not complete, since it doesn't take care of any special chars.

If you are using Rails you can go with this in yout views.
<%=h @code %>

A3d95ddbf619ce03ae9b9d2af3e157fd

Jits

February 14, 2010, February 14, 2010 11:11, permalink

No rating. Login to rate!

This should work directly in a Rail application.

In other scenarios you may need to require the CGI library.

x = "<my> Text & Tales"
y = CGI.escapeHTML(x)

Your refactoring





Format Copy from initial code

or Cancel