0

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.

Anton R
  • 181
  • 2
  • 11

3 Answers3

0

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.

Xiaohong Deng
  • 135
  • 2
  • 12
0

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
Leonard Kakande
  • 675
  • 1
  • 10
  • 17
-1

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
Rokibul Hasan
  • 4,078
  • 2
  • 19
  • 30