Rails 3 - How to escape flash message

475 views Asked by At

Should the flash message be escaped automatically by Rails? If not, how to ensure message gets escaped (without using CGI::escapeHTML)?

After doing some searching, I figured out that it should be escaped, and one got to html_safe a message to display html. But when I try

flash[:error] = "<b>YO</b>"

it is displayed as bold YO and not as <b>YO</b>. Note that string object is not html_safe itself.

3

There are 3 answers

1
Rokibul Hasan On

You should use html_safe in your controller for flash message that you want escaped. It remove the raw function from the view.

flash[:error] = "<b>YO</b>".html_safe
0
Xiaohong Deng On

the correct way to handle this is in the final place you display your flash message, which is most likely to be application.html.erb. change

<%= message %>

in

  <% flash.each do |message_type, message| %>
    <div class="alert alert-<%= message_type %>"><%= message %></div>
  <% end %>

to

<%= sanitize message %>

remember always apply sanitize to the string at the end point of the pipeline your string goes through to ensure you get your style.

0
Leonard Kakande On

the questions stated without using CGI::escapeHTML. You can use a ERB::Util.html_escape in the controller

flash[:error] = escape_html('<b>Yo</b>')
....

private
  def escape_html(string_to_escape)
    ERB::Util.html_escape(string_to_escape)
  end