Rails 4 - Toaster notifications rather than flash notifications

5.9k views Asked by At

I am using this library, (https://github.com/CodeSeven/toastr) and I am trying to push my Flash notifications to the javascript function Toastr has provided for me. How do I call this function for every error or notification?

This is one of the methods that are used for making a toaster notification:

toastr.warning('This is a warning!')

I tried making a method in the ApplicationController to see if I could call that method on default errors from CanCan. I have various versions of the method, none of which worked.

def toast(type, text)
    #if Logic here for various errors/notifications
    respond_to do |format|
        format.js { render action: "toastr.warning(#{text})", layout: false}
    end
end

def toast(type, text)
    #if Logic here for various errors/notifications
    "toastr.warning(#{text})"
end

And then I try to use this method in the CanCan block:

rescue_from CanCan::AccessDenied do |exception|
    toast :error, exception.message
    redirect_to root_url
end

I would assume that this is possible, but I am just unsure how to implement it. Not many try to do this, and there is probably a reason. I am open to any suggestions on how to do what I am trying to do.

Here is a testing application that implements the Toast notifications: http://codeseven.github.io/toastr/demo.html

1

There are 1 answers

1
pdobb On BEST ANSWER

What I'd recommend is to make a new flash type for this sort of thing and then render that as JS in your layout.

ApplicationController

def toast(type, text)
  flash[:toastr] = { type => text }
end


app/views/layouts/<your layout>.html.erb
# (or in a partial to be reused in various layouts)
# the <script> tag isn't needed if code snippet is
# included in an existing script block, of course.

<% if flash[:toastr] %>
  <script type="text/javascript">
    <% flash[:toastr].each do |type, message| %>
      toastr.<%= type %>(<%= message.inspect %>)
    <% end %>
  </script>
<% end %>

So this way you get all the standard behavior you're used to from the flash object and you get easy to understand javascript written in your views directly via erb. You may need to add an options hash to the ApplicationController#toast method so you can do a flash.now[:toastr] at times, of course. And so on... But this should get you started.