Nithin Bekal Posts About

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
  end
end

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

Nithin Bekal
Hi, I’m Nithin! This is my blog about programming. Ruby is my programming language of choice and the topic of most of my articles here, but I occasionally also write about Elixir, and sometimes about the books I read. I'm @nithinbekal on Twitter.