Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Flash message with html_safe from the controller in Rails 4 (safe version)

In my controller I have the following code:

    format.html { redirect_to new_customer_url,
                notice: %Q[ A customer already exists with with this shopping id. Edit this customer #{view_context.link_to("here", edit_customer_url(@duplicate))}.
    ].html_safe

I would like to be able to include a link in a flash message, so (as you can see) I call html_safe to unescape the string. However, it seems that as of Rails 4.1 this is now handled differently. (See here and here)

A solution to this has been provided in this question. However, it only does so by moving the html_safe call to the view, having the effect of unescaping all flash messages.

I would prefer to be a bit more paranoid than that, is there any way to include the link in the flash message from the controller?

like image 954
0112 Avatar asked Oct 23 '14 22:10

0112


1 Answers

Here is one possible way to solve this problem. Add a before filter to your ApplicationController which will make flash[:notice] html safe only if flash[:html_safe] is set. Then you can control when and when not to make notices html safe completely from the controller.

before_filter -> { flash.now[:notice] = flash[:notice].html_safe if flash[:html_safe] && flash[:notice] }

Then your example could be modified to this:

format.html do
  redirect_to(
    new_customer_url,
    notice: %Q[ A customer already exists with with this shopping id. Edit this customer #{view_context.link_to("here", edit_customer_url(@duplicate))}.],
    flash: { html_safe: true }
  )
end
like image 112
Wizard of Ogz Avatar answered Oct 21 '22 01:10

Wizard of Ogz