- Create file
connection.rb,notification_channel.rb,channel.rb - Install
redis
- Install deps with
npm i --save actioncablenpm i --save-dev @types/actioncable
- Create service
notifications.service.tsas below
# location: Gemfile.rb
gem 'redis'# location: rails/app/channels/notification_channel.rb
class NotificationChannel < ApplicationCable::Channel
def broadcast(channel, payload)
NotificationChannel.broadcast_to(channel, payload)
end
def subscribed
stream_from "notifications"
stream_for current_user
end
def receive(data)
puts "Received: #{data.inspect}"
ActionCable.server.broadcast 'notifications', { title: 'Data from server to client' }
# NotificationChannel.broadcast_to(current_user, payload) # From console/model/controller
end
end# location: rails/app/channels/application_cable/connection.rb
module ApplicationCable
class Connection < ActionCable::Connection::Base
identified_by :current_user
def connect
puts "request.params => #{request.params.inspect}"
reject_unauthorized_connection if request.params[:token].blank?
self.current_user = request.params[:token]
end
private
def report_error(e)
puts e.to_s + "\n" + e.backtrace.join("\n")
end
end
end#location: rails/app/channels/application_cable/channel.rb
module ApplicationCable
class Channel < ActionCable::Channel::Base
end
end mount ActionCable.server => '/cable'# location: config/cable.yml
development:
adapter: redis
url: <%= ENV.fetch("REDIS_URL") { 'redis://localhost:6379/1' } %>
channel_prefix: websocket# location: app/channels/notification_channel.rb
config.action_cable.disable_request_forgery_protection = true
# config.logger = Logger.new($stdout)
config.action_cable.url = "ws://localhost:8080/cable"... you should be fine :)