Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Best practice method of displaying flash messages

I'm wondering what's the best practice for displaying flash messages. The two main ways I've seen are using something like this scaffold generated code

<p id="notice"><%= notice %></p>

or placing code like this in your application header.

<% if !flash.empty? %>
    <div id="flash"> 
        <% flash.keys.each do |k| %> 
            <div class="<%= k %>">
                <%= flash[k] %>
            </div>  
        <% end %>   
    </div>
<% end %>

It appears to me that the first method adds more flexibility while the latter improves code readability and eliminates redundancy. Is there a method most rails developers prefer? As a side question how does scaffolding implement notice? Is it just a helper that accesses the flash hash? Why go through the trouble of using the helper when you can directly use the flash hash? Thanks

like image 806
Steve Avatar asked Feb 22 '12 07:02

Steve


People also ask

Where are flash messages stored?

They are stored in your session store. The default since rails 2.0 is the cookie store, but check in config/initializers/session_store.

How does Flash work in Rails?

Per the Rails Docs, flash is a middleware method that sends forward temporary datatypes which the Rails controller delegates to the request object. Now in plain English: flash is a method through which you can send a temporary string, array, or hash once between your otherwise stateless HTTP requests.


4 Answers

I'm doing it this way:

<% flash.each do |key, value| %>
  <%= content_tag :div, value, class: "flash #{key}" %>
<% end %>
like image 169
zolter Avatar answered Oct 21 '22 04:10

zolter


Calling a partial keeps your application.html.erb even cleaner..

<%= render 'shared/flash_messages' if !flash.empty? %>

.. and in the partial do something like what @zolter mentioned:

<div id="flash_messages">
  <% flash.each do |key, value| %>
    <%= content_tag(:div, value, :class => "flash #{key}") %>
  <% end %>
</div>
like image 44
user664833 Avatar answered Oct 21 '22 05:10

user664833


Why not put the second method on a helper function so it doesn't affect code readability on layouts?

like image 2
fjyaniez Avatar answered Oct 21 '22 04:10

fjyaniez


<% if flash[:notice] %>
  <div class="notification is-primary global-notification">
    <p class="notice"><%= notice %></p>
  </div>
<% end %>

<% if flash[:alert] %>
  <div class="notification is-danger global-notification">
    <p class="alert"><%= alert %></p>
  </div>
<% end %>
like image 1
Ümit Öztürk Avatar answered Oct 21 '22 04:10

Ümit Öztürk