Rails 4 - 使用弹窗通知而不是闪现通知

5
我将使用这个库(https://github.com/CodeSeven/toastr),并尝试将Flash通知推送到Toastr为我提供的JavaScript函数。如何在每个错误或通知时调用此函数?
以下是制作烤面包机通知的方法之一:
toastr.warning('This is a warning!')

我尝试在 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

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

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

我认为这是可能的,但我不确定如何实现它。很少有人尝试这样做,可能有原因。我愿意听取任何关于如何完成我想做的事情的建议。
这里有一个测试应用程序,实现了Toast通知: http://codeseven.github.io/toastr/demo.html
1个回答

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 %>

如此一来,您可以从flash对象中获得您所习惯的所有标准行为,并通过erb直接在视图中编写易于理解的javascript。当然,您可能需要向ApplicationController#toast方法添加选项哈希,以便在某些时候进行flash.now[:toastr]操作等等。但这应该能让您入门。


稍加调整,例如在 message.inspect 上添加 Raw。我让它工作了。感谢您的帮助! - Rizowski

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接