Escaping the flash
At work we’re building an online community site with the aim of promoting sustainable lifestyles – quite similar to A year of living generously
The deadline is fast approaching, and Matthew and I have been coding hard to meet it. Last week we were discussing what seemed to be a fairly generic problem – what’s the best way to HTML escape content you put in the flash?
We turned up this answer via google, which suggests escaping it when you render it in your view, i.e.
<%=h(flash[:notice])%>
All well and good, but sometimes you want a mixture of HTML and user generated content in the flash, e.g.
Sinbad has sent you a message
So escaping the lot is not really an option.
One solution is to use render_to_string with a partial as shown below:
Controller
def index
if current_user.messages.any?
flash[:notice] = render_to_string :partial => 'message',
:object => current_user.messages.first
end
# rest of action ...
end
Partial
<%= h(message.sender) %> has sent you a
<%= link_to "message", :controller => 'messages',
:action => 'show', :id => message %>
Layout
<div class="notice">
<%= flash[:notice] %>
</div>
I imagine :inline would also work, if a partial for a flash message seems like overkill.


