Refactoring Flash Message & Writing Helpers

In rails flash provides a way to pass temporary objects between actions. Anything you place in the flash will be exposed to the very next action and then cleared. It is used for showing notices and alerts e.g flash[:notice] = "Post successfully created"
I will be editing the blackbook demo app’s flash message, so that it is a helper which displays notice or alert bootstrap style.

1
2
3
4
5
6
7
8
9
10
11
12
13
<% if flash[:notice] %>
    <div class="alert alert-success">
      <button class="close" data-dismiss="alert">x</button>
      <%= flash[:notice] %>
    </div>
<% end %>
 
<% if flash[:alert] %>
    <div class="alert alert-error">
      <button class="close" data-dismiss="alert">x</button>
      <%= flash[:alert] %>
    </div>
<% end %>

In app/views/layouts/application.html.erb just before <%= yield %> I added the code above. I first check if there is a flash message for notice or :alert line 3 and 10 simply show a delete icon from twitter bootstrap, line 4 and 11 takes care of printing the actual flash message.

1
2
3
4
5
6
<% flash.each do |type, message| %>
    <div class="alert <%= flash_class type %>">
      <button class="close" data-dismiss="alert">x</button>
      <%= message %>
    </div>
<% end %>

There was a bit of code duplication in how I was displaying the flash messages, so I used rails helper to create a more streamlined version of flash message display above. Rather than using if statement as I did before to display notices and alerts, I used .each method on the flash object.
This simply goes through the flash and returns 2 symbols: type and message, type would be something line alert or notice and message would be the message to print out onto the screen.

Line 2 calls flash_class helper method, which takes in type as its argument, this method reurns alert-error or alert-success

1
2
3
4
5
6
7
8
9
10
def flash_class(type)
    case  type
	when :alert
		"alert-error"
	when :notice
		"alert-success"
	else
		""
    end
end

Above is the helper method I created, this is located within: app/helpers/application_helper.rb it accepts type variable and checks if it is :alert or :notice it then returns the right bootstrap class type. It defaults to an empty string provided in the else statement.