Escaping and Unescaping text in ERb

Instead of continuing the thread hijack, I’ve started a new one…

Douglas L. wrote:

2006/1/22, Kevin O. [email protected]:

You know, this has been bothering me a bit lately. If the point of
doing an html escape on the output is to prevent security problems,
wouldn’t it make sense for the default action on outputting data for it
to be html_escape’d?

Hmm, I think that it would just add confusion:

Example: <%= link_to :action => ‘something’ %>

That would then output escaped HTML, rather than a link.


Yes, that would be a problem using the current syntax.

The problem as I see it is that it is far too easy for someone to write
code like this…

<%= link_to :action=>‘something’ %> # should output html
<%= object.unsafe_string %> #should not output html

The relies on the programmer getting it right, and if they screw up,
they leave a gaping security hole. I’ve also seen many people asking
what ‘h’ means, which makes me concerned that it’s missing from quite a
few places where it should be.

I would rather have a format like this…

<%= unsafe(link_to :action=>‘something’) %> # outputs unescaped html
<%= object.unsafe_string %> #escaped html

That way if I forget to put an ‘h’ on my output the worst that can
happen is that it will render improperly. If you really want to over
ride that behavior, you can go a head and let the raw text out. But
since it would have to be a deliberate action, it is less likely to be a

Is there a downside to this approach that I don’t see? How about an
easy way to implement it?

One possible way I can see doing it would be to over ride the
activerecord method that returns attributes. It could be modified so
that a format like…

object.attribute #=>returns escaped version of ‘attribute’
object.unsafe_attribute #=>returns raw version

Interesting… we could use this method to create a functional version
of Apps Hungarian that performs some actions on attributes before
returning them.


This forum is not affiliated to the Ruby language, Ruby on Rails framework, nor any Ruby applications discussed here.

| Privacy Policy | Terms of Service | Remote Ruby Jobs