Today I Learned

Easily add Toastr flash notices to Rails apps

I learned about Toastr JavaScript library last week and have been delighted to use it instead of more traditional flash messaging.

First of all get the Toastr sources. I opted to link to them on CDNJS:

= stylesheet_link_tag ''
= javascript_include_tag ''

Next I defined some extra flash types in my application_controller.rb file to match Toastr's native notification types and enable use of the built-in styling.

class ApplicationController < ActionController::Base
  add_flash_types :success, :info, :warning, :error

Finally, add the following block of JavaScript to the bottom of a layout template (or whatever shared partial that contains your JS and CSS includes.

- flash.keys.each do |key|
  - toastr_key = key
  - toastr_key = 'info' if key == 'notice'
  - toastr_key = 'warning' if key == 'alert'
    $(function() {

Lines 2 and 3 establish a mapping from conventional Rails notice and alert so that I don't have to hack libraries like Devise which rely on them.



The "Bible" of Ruby on Rails is better than ever

For a limited time, get half off the ultimate The Rails 5 Way package

The "Future Proof Package" is available to TIL readers for only $20. It includes The Rails 5 Way, plus early access to Obie's next two books: Mastering The Rails Way and Testing The Rails Way

Looking for help? Obie Fernandez of Kickass Consulting has been the foremost industry expert on Ruby on Rails development for over 10 years. Rails is a core skill for each developer at Kickass Consulting and we'd love to take a look at your project. Contact us today and find out how we can help you.