Nithin Bekal Posts About Notes

Bootstrap flash messages in Rails

14 May 2015

After avoiding Bootstrap for so long, I’m starting to see some of the advantages that it offers. For instance, I needed to style flash messages today, and turn out, I don’t have to write any CSS for it. This is all the code I needed:

/ app/views/layouts/application.haml
= render 'shared/flash'
/ app/views/shared/_flash.haml
- flash.each do |type, message|
  %div{ class: "alert #{bootstrap_flash_class(type)} fade in" }
    = message
    %button.close{ data: { dismiss: 'alert' } } x

Then we add a simple helper method to translate the flash classes to the bootstrap flash class names:

module ApplicationHelper
  def bootstrap_flash_class(flash_type)
    { success: 'alert-success',
      error:   'alert-danger',
      alert:   'alert-warning',
      notice:  'alert-info'
    }[flash_type.to_sym] || flash_type.to_s

Maybe it’s not such bad idea to start new projects with Bootstrap after all.

Nithin Bekal
Hi, I’m Nithin Bekal. I work at Shopify in Ottawa, Canada. Previously, co-founder of and WowMakers. Ruby is my preferred programming language, and the topic of most of my articles here, but I'm also a big fan of Elixir. Tweet to me at @nithinbekal.