Rails Flash Messages Styles

Rails Flash Messages Styles

If you’re using Ruby on Rails with Twitter Bootstrap or other css framworks, then you may want to display flash messages with the alert styles. Here is a quick and easy way of doing so.

You just need to quickly extend application_helper.rb with the following:

application_helper.rb
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
module ApplicationHelper
  def bootstrap_class_for(flash_type)
    case flash_type
      when "success"
        "alert-success"
      when "error"
        "alert-danger"
      when "alert"
        "alert-warning"
      when "notice"
        "alert-info"
      else
        flash_type.to_s
      end
  end
end

Now when you call a flash message, you can use the following in your view:

1
2
3
4
5
6
<% flash.each do |type, message| %>
  <div class="alert <%= bootstrap_class_for(type) %> alert-dismissible" role="alert">
    <button type="button" class="close" data-dismiss="alert" aria-label="Close"><span aria-hidden="true">&times;</span></button>
    <%= message %>
  </div>
<% end %>

And just use:

1
flash[:success] = "Credit card type saved successfully!"

As success message:

1
flash[:alert] = "Alerting you to the monkey on your car!"

So far so good, That’s it!!! See ya!!! :)