aboutsummaryrefslogtreecommitdiffstats
path: root/lib/action_cable/channel/streams.rb
diff options
context:
space:
mode:
Diffstat (limited to 'lib/action_cable/channel/streams.rb')
-rw-r--r--lib/action_cable/channel/streams.rb40
1 files changed, 40 insertions, 0 deletions
diff --git a/lib/action_cable/channel/streams.rb b/lib/action_cable/channel/streams.rb
new file mode 100644
index 0000000000..3eac776e61
--- /dev/null
+++ b/lib/action_cable/channel/streams.rb
@@ -0,0 +1,40 @@
+module ActionCable
+ module Channel
+ module Streams
+ extend ActiveSupport::Concern
+
+ included do
+ on_unsubscribe :stop_all_streams
+ end
+
+ def stream_from(broadcasting, callback = nil)
+ callback ||= default_stream_callback(broadcasting)
+
+ streams << [ broadcasting, callback ]
+ pubsub.subscribe broadcasting, &callback
+
+ logger.info "#{channel_name} is streaming from #{broadcasting}"
+ end
+
+ def stop_all_streams
+ streams.each do |broadcasting, callback|
+ pubsub.unsubscribe_proc broadcasting, callback
+ logger.info "#{channel_name} stopped streaming from #{broadcasting}"
+ end
+ end
+
+ private
+ delegate :pubsub, to: :connection
+
+ def streams
+ @_streams ||= []
+ end
+
+ def default_stream_callback(broadcasting)
+ -> (message) do
+ transmit ActiveSupport::JSON.decode(message), via: "streamed from #{broadcasting}"
+ end
+ end
+ end
+ end
+end