Nice Flash Messages in Rails 4 with Bootstrap

28 Jun 16

Add this to your application layouts view file to enable it to be global to your app:

<!-- app/views/layouts/application.html.erb
<% flash.each do |type, message| %>
  <div class="alert <%= flash_class(type) %> fade in">
    <%= message %>
  </div>
<% end %>

Create a simple little helper:

# app/helpers/application_helper.rb
module ApplicationHelper
  def flash_class(type)
    { success: 'alert-success',
      error:   'alert-danger',
      alert:   'alert-warning',
      notice:  'alert-info'
    }[type] || type.to_s
  end
end

Add this to your javascript to enable the message to fade away:

// app/assets/my_apps.coffee
$(document).on('page:change', function() {
  $('.alert').delay(2000).slideUp(500, function() {
    $('.alert').alert('close');
  });
});

$(document).ready(ready)
$(document).on('page:load', ready)