Skip to content

Instantly share code, notes, and snippets.

@rsmithlal
Created July 19, 2023 14:54
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save rsmithlal/23853772375a6d89bbee3604848fe7c8 to your computer and use it in GitHub Desktop.
Save rsmithlal/23853772375a6d89bbee3604848fe7c8 to your computer and use it in GitHub Desktop.
Create and subscribe to Rails API Action Cable for notification on Vue.js 2 app
// app/javascript/channels/notification.js
import consumer from "./consumer";
consumer.subscriptions.create({ channel: "NotificationChannel" }, {
connected() {
console.log("Connected to the notification channel");
},
disconnected() {
console.log("Disconnected from the notification channel");
},
received(data) {
console.log("Received notification:", data);
// Handle the notification data in your Vue.js application
}
});
// In the above code, we're creating a consumer object and subscribing to the NotificationChannel.
// The received function will be called whenever a new notification is broadcasted to the channel.
// You can handle the notification data according to your requirements within the received function.
# app/channels/notification_channel.rb
class NotificationChannel < ApplicationCable::Channel
def subscribed
stream_from "notifications_#{current_user.id}"
end
def unsubscribed
# Any cleanup needed when the channel is unsubscribed
end
def send_notification(data)
ActionCable.server.broadcast("notifications_#{current_user.id}", data)
end
end
# In the above code, we define a NotificationChannel class that inherits from ApplicationCable::Channel.
# In the subscribed method, we're subscribing the current user to a specific channel named "notifications_<user_id>".
# This allows Action Cable to broadcast notifications to that specific channel. The unsubscribed method can be used for
# any cleanup tasks when the channel is unsubscribed.
# config/routes.rb
Rails.application.routes.draw do
# ...
mount ActionCable.server => '/cable'
# ...
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment