Tigraine

Daniel Hoelbling-Inzko talks about programming

When to use raw() and when to use .html_safe

Posted by Daniel Hölbling on August 23, 2012

What rails does very nicely is protect you from XSS attacks through aggressively HTML encoding anything you write between <%= %>. But there is one caveat: At times you may really want to render HTML from a string. So you need to tell rails not to escape your HTML in that case.

There are two methods of telling rails that a string is safe and should not be escaped: raw and .htmlsafe

And both do the same. They mark the string as safe (through the use of the html safe buffer) and rails will not encode it any more. The main difference between the two: nil.

If you are doing things like: "<img src='#{..}' />".html_safe .html_safe is totally fine as the string will never be nil, but if you are dealing with strings that may be nil .html_safe will break since there is no .html_safe method on the nil object. (For example if you are loading something from a config value or the database) In that case using raw(...) will just ignore the string instead of raising an exception.

As always with these things: raw and html_safe make it very easy to introduce XSS attack vectors into your application. So use them wisely and only on strings you are sure to be safe.

Filed under programmierung, rails, ruby
comments powered by Disqus

My Photography business

Projects

dynamic css for .NET

Archives

more