what the best way for escape html with rails 4: gsub('<', '&lt;') OR CGI.escapeHTML

615 views Asked by At

I want escape html for data in controller, I found 2 ways:

text.gsub('<', '&lt;').gsub('>', '&gt;')

OR

CGI.escapeHTML(text)

What is the best, why?

1

There are 1 answers

3
Adam D. Ruppe On

The best way is probably to just assign the data to instance variables and then output them in the view, which will handle encoding automatically:

controller:

def something
  @foo = "<test>"
end

something.html.erb

<%= @foo %>

Will output:

&lt;test&gt;

The view will do the right thing in most cases.