1
0
Fork 0
mirror of https://github.com/rails/rails.git synced 2022-11-09 12:12:34 -05:00
rails--rails/actioncable/lib/action_cable/server/broadcasting.rb

55 lines
2.4 KiB
Ruby
Raw Normal View History

# frozen_string_literal: true
2015-06-28 14:24:50 -04:00
module ActionCable
module Server
# Broadcasting is how other parts of your application can send messages to a channel's subscribers. As explained in Channel, most of the time, these
2015-07-07 17:13:00 -04:00
# 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
2015-07-07 17:13:00 -04:00
#
# # Somewhere in your app this is called, perhaps from a NewCommentJob:
# ActionCable.server.broadcast \
# "web_notifications_1", { title: "New things!", body: "All that's fit for print" }
2015-07-07 17:13:00 -04:00
#
# # Client-side CoffeeScript, 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']
2015-06-28 14:24:50 -04:00
module Broadcasting
# Broadcast a hash directly to a named <tt>broadcasting</tt>. This will later be JSON encoded.
def broadcast(broadcasting, message, coder: ActiveSupport::JSON)
broadcaster_for(broadcasting, coder: coder).broadcast(message)
end
2016-02-13 06:36:16 -05:00
# Returns a broadcaster for a named <tt>broadcasting</tt> that can be reused. Useful when you have an object that
2015-07-07 17:13:00 -04:00
# may need multiple spots to transmit to a specific broadcasting over and over.
def broadcaster_for(broadcasting, coder: ActiveSupport::JSON)
Broadcaster.new(self, String(broadcasting), coder: coder)
2015-06-28 14:24:50 -04:00
end
2015-06-28 14:42:49 -04:00
private
class Broadcaster
attr_reader :server, :broadcasting, :coder
2015-06-28 14:42:49 -04:00
def initialize(server, broadcasting, coder:)
@server, @broadcasting, @coder = server, broadcasting, coder
end
2015-06-28 14:24:50 -04:00
def broadcast(message)
server.logger.debug { "[ActionCable] Broadcasting to #{broadcasting}: #{message.inspect.truncate(300)}" }
payload = { broadcasting: broadcasting, message: message, coder: coder }
ActiveSupport::Notifications.instrument("broadcast.action_cable", payload) do
encoded = coder ? coder.encode(message) : message
server.pubsub.broadcast broadcasting, encoded
end
end
2015-06-28 14:24:50 -04:00
end
end
end
end