DEV Community

Cover image for Ruby on Rails 6: Disappearing flash messages with toastr
Yaroslav Shmarov
Yaroslav Shmarov

Posted on • Originally published at blog.corsego.com on

Ruby on Rails 6: Disappearing flash messages with toastr

Source library: https://github.com/CodeSeven/toastr

Installation:

console:

yarn add toastr
Enter fullscreen mode Exit fullscreen mode

Import toastr in app/javascripts/packs/application.js:

global.toastr = require("toastr")
Enter fullscreen mode Exit fullscreen mode

app/javascript/stylesheets/application.scss:

@import 'toastr'
Enter fullscreen mode Exit fullscreen mode

app/javascript/packs/application.js:

import "../stylesheets/application"
Enter fullscreen mode Exit fullscreen mode

app/views/layouts/application.rb:

<% unless flash.empty? %>
   <script type="text/javascript">
      <% flash.each do |f| %>
    <% type = f[0].to_s.gsub('alert', 'error').gsub('notice', 'info') %>
     toastr['<%= type %>']('<%= f[1] %>');
   <% end %>
   </script>
<% end %>
Enter fullscreen mode Exit fullscreen mode

customizing the flash:

<% unless flash.empty? %>
  <script type="text/javascript">
    <% flash.each do |f| %>
        <% type = f[0].to_s.gsub('alert', 'error').gsub('notice', 'info') %>
        toastr['<%= type %>']('<%= f[1] %>', '', {
          "closeButton": true,
          "positionClass": "toast-top-center", 
          "onclick": null, 
          "showDuration": "300", 
          "hideDuration": "1000", 
          "timeOut": "5000", 
          "extendedTimeOut": "1000", 
          "showEasing": "swing", 
          "hideEasing": "linear", 
          "showMethod": "fadeIn", 
          "progressBar": true,
          "hideMethod": "fadeOut" });
    <% end %>
  </script>
<% end %>
Enter fullscreen mode Exit fullscreen mode

Footnote: require("stylesheets/application.scss") = import "../stylesheets/application"

Final result:

flash-message-example

Top comments (4)

Collapse
 
sturpin profile image
Sergio Turpín • Edited

I like your post because they are clear and concise 😄 I didn't know toastr, Thanks!!!

Collapse
 
alexohre profile image
Ohre Alex Oghenebrorhien

hello, thanks for your post.
please how do i use this in rails 7

Collapse
 
niyanta_zamindar_63b4bdbc profile image
Niyanta Zamindar

Amazing one dude!

Collapse
 
williamvu1999 profile image
William-Vu-1999

I am your fan, learn a lot from your course udemy.