Rails 5 API +实时通知

时间:2016-10-26 21:03:30

标签: redis ruby-on-rails-5 rails-api actioncable

我只创建了一个Rails 5 API,我需要创建一个实时网络通知。

使用ActionCable可以实现吗?有没有人有Action Cable或任何其他解决方案的例子?

提前致谢。

1 个答案:

答案 0 :(得分:5)

这是一个网络通知渠道,允许您在向正确的广播流广播时触发客户端网络通知:

创建服务器端Web通知渠道:

# app/channels/web_notifications_channel.rb
class WebNotificationsChannel < ApplicationCable::Channel
  def subscribed
    stream_for current_user
  end
end

创建客户端网络通知频道订阅:

# app/assets/javascripts/cable/subscriptions/web_notifications.coffee
# Client-side which assumes you've already requested
# the right to send web notifications.
App.cable.subscriptions.create "WebNotificationsChannel",
  received: (data) ->
    new Notification data["title"], body: data["body"]

从应用程序的其他位置向Web通知渠道实例广播内容:

# Somewhere in your app this is called, perhaps from a NewCommentJob
WebNotificationsChannel.broadcast_to(
  current_user,
  title: 'New things!',
  body: 'All the news fit to print'
)

WebNotificationsChannel.broadcast_to调用将消息放在当前订阅适配器的pubsub队列中,每个用户使用一个单独的广播名称。对于ID为1的用户,广播名称为web_notifications:1