Rails 4 - Toaster通知而不是Flash通知

Riz*_*ski 5 javascript notifications ruby-on-rails toastr ruby-on-rails-4

我正在使用这个库,(https://github.com/CodeSeven/toastr),我正在尝试将我的Flash通知推送到Toastr为我提供的javascript函数.如何为每个错误或通知调用此函数?

这是用于制作烤面包机通知的方法之一:

toastr.warning('This is a warning!')
Run Code Online (Sandbox Code Playgroud)

我尝试在ApplicationController中创建一个方法,看看我是否可以在CanCan的默认错误上调用该方法.我有各种版本的方法,没有一个工作.

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
Run Code Online (Sandbox Code Playgroud)

然后我尝试在CanCan块中使用此方法:

rescue_from CanCan::AccessDenied do |exception|
    toast :error, exception.message
    redirect_to root_url
end
Run Code Online (Sandbox Code Playgroud)

我认为这是可能的,但我只是不确定如何实现它.没有多少人尝试这样做,可能有一个原因.我对如何做我想做的任何建议持开放态度.

这是一个实现Toast通知的测试应用程序:http: //codeseven.github.io/toastr/demo.html

pdo*_*obb 5

flash我的建议是为这类事情创建一个新类型,然后在布局中将其渲染为 JS。

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 %>
Run Code Online (Sandbox Code Playgroud)

因此,通过这种方式,您可以从对象中获得您习惯的所有标准行为flash,并且可以轻松理解直接通过 erb 在视图中编写的 JavaScript。当然,您可能需要向该方法添加选项哈希ApplicationController#toast,以便有时可以执行 a 操作。flash.now[:toastr]等等...但这应该让您开始。