diff options
-rw-r--r-- | lib/action_cable/channel.rb | 1 | ||||
-rw-r--r-- | lib/action_cable/channel/base.rb | 1 | ||||
-rw-r--r-- | lib/action_cable/channel/redis.rb | 32 |
3 files changed, 34 insertions, 0 deletions
diff --git a/lib/action_cable/channel.rb b/lib/action_cable/channel.rb index a54302d30f..94cdc8d722 100644 --- a/lib/action_cable/channel.rb +++ b/lib/action_cable/channel.rb @@ -1,6 +1,7 @@ module ActionCable module Channel autoload :Callbacks, 'action_cable/channel/callbacks' + autoload :Redis, 'action_cable/channel/redis' autoload :Base, 'action_cable/channel/base' end end diff --git a/lib/action_cable/channel/base.rb b/lib/action_cable/channel/base.rb index 7052945eb1..40af1462b4 100644 --- a/lib/action_cable/channel/base.rb +++ b/lib/action_cable/channel/base.rb @@ -3,6 +3,7 @@ module ActionCable class Base include Callbacks + include Redis on_subscribe :start_periodic_timers on_unsubscribe :stop_periodic_timers diff --git a/lib/action_cable/channel/redis.rb b/lib/action_cable/channel/redis.rb new file mode 100644 index 0000000000..215cc3c975 --- /dev/null +++ b/lib/action_cable/channel/redis.rb @@ -0,0 +1,32 @@ +module ActionCable + module Channel + + module Redis + extend ActiveSupport::Concern + + included do + on_unsubscribe :unsubscribe_from_redis_channels + end + + def subscribe_to(redis_channel, callback = nil) + @_redis_channels ||= [] + @_redis_channels << redis_channel + + callback ||= -> (message) { broadcast ActiveSupport::JSON.decode(message) } + redis.pubsub.subscribe(redis_channel, &callback) + end + + protected + def unsubscribe_from_redis_channels + if @_redis_channels + @_redis_channels.each { |channel| @connection.pubsub.unsubscribe(channel) } + end + end + + def redis + @connection.redis + end + end + + end +end
\ No newline at end of file |