Rails 5 API +实时通知

Pas*_*uby 4 redis rails-api ruby-on-rails-5 actioncable

我只创建一个Rails 5 API,我需要创建一个实时的Web通知.

这可以通过使用ActionCable吗?有没有人有行动电缆或任何其他解决方案的例子?

提前致谢.

Vik*_*tor 5

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

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

# app/channels/web_notifications_channel.rb
class WebNotificationsChannel < ApplicationCable::Channel
  def subscribed
    stream_for current_user
  end
end
Run Code Online (Sandbox Code Playgroud)

创建客户端Web通知渠道订阅:

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

从应用程序的其他位置向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'
)
Run Code Online (Sandbox Code Playgroud)

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