2015-06-28 14:24:50 -04:00
|
|
|
module ActionCable
|
|
|
|
module Server
|
2015-07-07 17:13:00 -04:00
|
|
|
# Broadcasting is how other parts of your application can send messages to the channel subscribers. As explained in Channel, most of the time, these
|
|
|
|
# broadcastings are streamed directly to the clients subscribed to the named broadcasting. Let's explain with a full-stack example:
|
|
|
|
#
|
|
|
|
# class WebNotificationsChannel < ApplicationCable::Channel
|
|
|
|
# def subscribed
|
|
|
|
# stream_from "web_notifications_#{current_user.id}"
|
|
|
|
# end
|
|
|
|
# end
|
|
|
|
#
|
|
|
|
# # Somewhere in your app this is called, perhaps from a NewCommentJob
|
|
|
|
# ActionCable.server.broadcast \
|
|
|
|
# "web_notifications_1", { title: 'New things!', body: 'All shit fit for print' }
|
|
|
|
#
|
2015-12-18 02:32:17 -05:00
|
|
|
# # Client-side coffescript, which assumes you've already requested the right to send web notifications
|
2015-07-08 10:10:33 -04:00
|
|
|
# App.cable.subscriptions.create "WebNotificationsChannel",
|
2015-07-07 17:13:00 -04:00
|
|
|
# received: (data) ->
|
2015-07-08 23:22:56 -04:00
|
|
|
# new Notification data['title'], body: data['body']
|
2015-06-28 14:24:50 -04:00
|
|
|
module Broadcasting
|
2015-07-07 17:13:00 -04:00
|
|
|
# Broadcast a hash directly to a named <tt>broadcasting</tt>. It'll automatically be JSON encoded.
|
2015-06-28 15:17:16 -04:00
|
|
|
def broadcast(broadcasting, message)
|
|
|
|
broadcaster_for(broadcasting).broadcast(message)
|
2015-06-28 14:36:10 -04:00
|
|
|
end
|
|
|
|
|
2015-07-07 17:13:00 -04:00
|
|
|
# Returns a broadcaster for a named <tt>broadcasting</tt> that can be reused. Useful when you have a object that
|
|
|
|
# may need multiple spots to transmit to a specific broadcasting over and over.
|
2015-06-28 15:17:16 -04:00
|
|
|
def broadcaster_for(broadcasting)
|
|
|
|
Broadcaster.new(self, broadcasting)
|
2015-06-28 14:24:50 -04:00
|
|
|
end
|
|
|
|
|
2015-06-28 14:42:49 -04:00
|
|
|
private
|
2015-06-28 14:36:10 -04:00
|
|
|
class Broadcaster
|
2015-06-28 15:17:16 -04:00
|
|
|
attr_reader :server, :broadcasting
|
2015-06-28 14:42:49 -04:00
|
|
|
|
2015-06-28 15:17:16 -04:00
|
|
|
def initialize(server, broadcasting)
|
|
|
|
@server, @broadcasting = server, broadcasting
|
2015-06-28 14:36:10 -04:00
|
|
|
end
|
2015-06-28 14:24:50 -04:00
|
|
|
|
2015-06-28 14:38:05 -04:00
|
|
|
def broadcast(message)
|
2015-06-28 15:17:16 -04:00
|
|
|
server.logger.info "[ActionCable] Broadcasting to #{broadcasting}: #{message}"
|
2016-01-14 00:25:41 -05:00
|
|
|
server.adapter.broadcast broadcasting, ActiveSupport::JSON.encode(message)
|
2015-06-28 14:36:10 -04:00
|
|
|
end
|
2015-06-28 14:24:50 -04:00
|
|
|
end
|
|
|
|
end
|
|
|
|
end
|
2015-10-16 04:02:22 -04:00
|
|
|
end
|