Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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?

like image 717
lakesare Avatar asked May 14 '14 16:05

lakesare


People also ask

What is sanitize in Ruby?

Sanitize is an allowlist-based HTML and CSS sanitizer. It removes all HTML and/or CSS from a string except the elements, attributes, and properties you choose to allow.

What does Html_safe do in Rails?

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.

What does HTML safe mean?

Safe HTML is a module that filter the input before the content is stored in the database. Unlike Drupal basic filtering system, Safe HTML filter the form post and perform code cleaning before the content is stored on the site backend.


1 Answers

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.

like image 116
lakesare Avatar answered Sep 24 '22 08:09

lakesare