Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do you add toastr-rails gem to Rails 6 project?

I am trying to add the toastr gem to my Rails 6 project. I also have the devise gem installed.

I do not understand webpacker and how to make toastr-rails webpacker friendly.

I have read all the documentation. Don't tell me to read the documentation.

This is what I've tried:

yarn add toastr

Then in my assets/packs/application.js file, I added:

@import 'toastr'

And in my assets/stylesheets/application.scss file, I added:

*= require_toastr

Finally my layouts/application.html.erb has this code:

<!DOCTYPE html>
<html>
 <head>
 </head>
 <body>
  <% unless flash.empty? %>
    <script type="text/javascript">
        <% flash.each do |f| %>
        <% type = f[0].to_s %>
        toastr['<%= type %>']('<%= f[1] %>');
        <% end %>
    </script>
  <% end %>
  <%= yield %>
 </body>
</html>

I don't get the toast notifications. I don't get any notifications. But this code works on my Rails 4 project.

like image 680
David Lee Avatar asked Dec 01 '22 13:12

David Lee


1 Answers

If you want to add toastr with toastr-rails gem, use asset pipeline instead of webpack.

Here are the steps to add toastr with the webpack.

  1. Add toastr js with yarn

    yarn add toastr
    
  2. Require toastr in app/javascript/packs/application.js. I added it to the global to avoid errors

    global.toastr = require("toastr")
    
  3. Create app/javascript/stylesheets/application.scss file to import custom or library css files

  4. Import toastr css in app/javascript/stylesheets/application.scss

    @import 'toastr'
    
  5. Import app/javascript/stylesheets/application.scss file in app/javascript/packs/application.js

    import "../stylesheets/application"
    
  6. I wrote a helper method for flash messages. Add this method to application_helper.rb or another helper

    def toastr_flash
      flash.each_with_object([]) do |(type, message), flash_messages|
        type = 'success' if type == 'notice'
        type = 'error' if type == 'alert'
        text = "<script>toastr.#{type}('#{message}', '', { closeButton: true, progressBar: true })</script>"
        flash_messages << text.html_safe if message
      end.join("\n").html_safe
    end
    
  7. Add toastr_flash method to layouts/application.html.erb or wherever you want

    <!DOCTYPE html>
    <html>
      <head>
      </head>
      <body>
        <%= yield %>
        <%= toastr_flash %>
      </body>
    </html>
    
like image 95
demir Avatar answered Dec 04 '22 10:12

demir