raw vs. html_safe vs. h to unescape html

grautur picture grautur · Nov 23, 2010 · Viewed 271.5k times · Source

Suppose I have the following string

@x = "<a href='#'>Turn me into a link</a>"

In my view, I want a link to be displayed. That is, I don't want everything in @x to be unescaped and displayed as a string. What's the difference between using

<%= raw @x %>
<%= h @x %>
<%= @x.html_safe %>

?

Answer

F&#225;bio Batista picture Fábio Batista · Nov 23, 2010

Considering Rails 3:

html_safe actually "sets the string" as HTML Safe (it's a little more complicated than that, but it's basically it). This way, you can return HTML Safe strings from helpers or models at will.

h can only be used from within a controller or view, since it's from a helper. It will force the output to be escaped. It's not really deprecated, but you most likely won't use it anymore: the only usage is to "revert" an html_safe declaration, pretty unusual.

Prepending your expression with raw is actually equivalent to calling to_s chained with html_safe on it, but is declared on a helper, just like h, so it can only be used on controllers and views.

"SafeBuffers and Rails 3.0" is a nice explanation on how the SafeBuffers (the class that does the html_safe magic) work.