Reputation: 977
I'm creating a Rails 5 API only and I need to create a real time web notifications.
Is that possible by using ActionCable? Does anyone has an example of Action Cable or any other solution?
Thanks in advance.
Upvotes: 4
Views: 1524
Reputation: 4346
This is a web notification channel that allows you to trigger client-side web notifications when you broadcast to the right streams:
Create the server-side web notifications channel:
# app/channels/web_notifications_channel.rb
class WebNotificationsChannel < ApplicationCable::Channel
def subscribed
stream_for current_user
end
end
Create the client-side web notifications channel subscription:
# 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"]
Broadcast content to a web notification channel instance from elsewhere in your application:
# 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'
)
The WebNotificationsChannel.broadcast_to
call places a message in the current subscription adapter's pubsub queue under a separate broadcasting name for each user. For a user with an ID of 1, the broadcasting name would be web_notifications:1
.
Upvotes: 5