aboutsummaryrefslogtreecommitdiffstats
path: root/lib/action_cable/channel/redis.rb
blob: bdd6ab9dcf0abcb869e2fdd14eaa2be3b07d8cd7 (plain) (blame)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
module ActionCable
  module Channel
    module Redis
      extend ActiveSupport::Concern

      included do
        on_unsubscribe :unsubscribe_from_all_channels
        delegate :pubsub, to: :connection
      end

      def subscribe_to(redis_channel, callback = nil)
        callback ||= default_subscription_callback(redis_channel)
        @_redis_channels ||= []
        @_redis_channels << [ redis_channel, callback ]

        pubsub.subscribe(redis_channel, &callback)
        logger.info "#{channel_name} subscribed to incoming actions from #{redis_channel}"
      end

      def unsubscribe_from_all_channels
        if @_redis_channels
          @_redis_channels.each do |redis_channel, callback|
            pubsub.unsubscribe_proc(redis_channel, callback)
            logger.info "#{channel_name} unsubscribed from incoming actions #{redis_channel}"
          end
        end
      end

      protected
        def default_subscription_callback(channel)
          -> (message) do
            transmit ActiveSupport::JSON.decode(message), via: "incoming action from #{channel}"
          end
        end
    end
  end
end