How to HTML encode/escape a string? Is there a built-in?

ghz 1years ago ⋅ 2424 views

Question

I have an untrusted string that I want to show as text in an HTML page. I need to escape the chars '<' and '&' as HTML entities. The less fuss the better.

I'm using UTF8 and don't need other entities for accented letters.

Is there a built-in function in Ruby or Rails, or should I roll my own?


Answer

The h helper method:

<%=h "<p> will be preserved" %>