Ruby on Rails: difference between .html_safe and sanitize()

lakesare picture lakesare · May 14, 2014 · Viewed 9.7k times · Source

I have two pieces of code in my view:

<%= sanitize('<h3>winter</h3>') %>

<%= '<h3>winter</h3>'.html_safe %>

And they both seem to result in encoding html tags in a string provided. What is the difference between them and when should I use either?

Answer

lakesare picture lakesare · Mar 23, 2015

Those are two very different methods.

a = a.html_safe will just mark string a as 'html_safe' and treat it as such afterwards (Marks a string as trusted safe. It will be inserted into HTML with no additional escaping performed. It is your responsibility to ensure that the string contains no malicious content. This method is equivalent to the raw helper in views. It is recommended that you use sanitize instead of this method. It should never be called on user input.).

a.sanitize, on the other hand, will html encode all tags and strip all attributes that are not specifically allowed (you can add/remove allowed tags and attributes if you want). Notice that user input is sanitized by default unless you specifically allowed html-markup with raw (http://apidock.com/rails/ActionView/Helpers/OutputSafetyHelper/raw), which, by the way, uses html_safe to mark it as such.