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

52 lines
2.1 KiB
Ruby
Raw Normal View History

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' }
#
# # 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) ->
# web_notification = 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.
def broadcast(broadcasting, message)
broadcaster_for(broadcasting).broadcast(message)
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.
def broadcaster_for(broadcasting)
Broadcaster.new(self, broadcasting)
2015-06-28 14:24:50 -04:00
end
2015-07-07 17:13:00 -04:00
# The redis instance used for broadcasting. Not intended for direct user use.
2015-06-28 14:42:49 -04:00
def broadcasting_redis
@broadcasting_redis ||= Redis.new(config.redis)
2015-06-28 14:42:49 -04:00
end
2015-06-28 14:24:50 -04:00
2015-06-28 14:42:49 -04:00
private
class Broadcaster
attr_reader :server, :broadcasting
2015-06-28 14:42:49 -04:00
def initialize(server, broadcasting)
@server, @broadcasting = server, broadcasting
end
2015-06-28 14:24:50 -04:00
def broadcast(message)
server.logger.info "[ActionCable] Broadcasting to #{broadcasting}: #{message}"
server.broadcasting_redis.publish broadcasting, message.to_json
end
2015-06-28 14:24:50 -04:00
end
end
end
end