aboutsummaryrefslogtreecommitdiffstats
path: root/lib/action_cable/channel
diff options
context:
space:
mode:
Diffstat (limited to 'lib/action_cable/channel')
-rw-r--r--lib/action_cable/channel/base.rb64
-rw-r--r--lib/action_cable/channel/callbacks.rb32
2 files changed, 96 insertions, 0 deletions
diff --git a/lib/action_cable/channel/base.rb b/lib/action_cable/channel/base.rb
new file mode 100644
index 0000000000..82c1a14b49
--- /dev/null
+++ b/lib/action_cable/channel/base.rb
@@ -0,0 +1,64 @@
+module ActionCable
+ module Channel
+
+ class Base
+ include Callbacks
+
+ on_subscribe :start_periodic_timers
+ on_unsubscribe :stop_periodic_timers
+
+ attr_reader :params
+
+ class << self
+ def matches?(identifier)
+ raise "Please implement #{name}#matches? method"
+ end
+ end
+
+ def initialize(connection, channel_identifier, params = {})
+ @connection = connection
+ @channel_identifier = channel_identifier
+ @_active_periodic_timers = []
+ @params = params
+
+ setup
+ end
+
+ def receive(data)
+ raise "Not implemented"
+ end
+
+ def subscribe
+ self.class.on_subscribe_callbacks.each do |callback|
+ EM.next_tick { send(callback) }
+ end
+ end
+
+ def unsubscribe
+ self.class.on_unsubscribe.each do |callback|
+ EM.next_tick { send(callback) }
+ end
+ end
+
+ protected
+ def setup
+ # Override in subclasses
+ end
+
+ def publish(data)
+ @connection.publish(data.merge(identifier: @channel_identifier).to_json)
+ end
+
+ def start_periodic_timers
+ self.class.periodic_timers.each do |method, options|
+ @_active_periodic_timers << EventMachine::PeriodicTimer.new(options[:every]) { send(method) }
+ end
+ end
+
+ def stop_periodic_timers
+ @_active_periodic_timers.each {|t| t.cancel }
+ end
+ end
+
+ end
+end \ No newline at end of file
diff --git a/lib/action_cable/channel/callbacks.rb b/lib/action_cable/channel/callbacks.rb
new file mode 100644
index 0000000000..cf0246a386
--- /dev/null
+++ b/lib/action_cable/channel/callbacks.rb
@@ -0,0 +1,32 @@
+module ActionCable
+ module Channel
+
+ module Callbacks
+ extend ActiveSupport::Concern
+
+ included do
+ class_attribute :on_subscribe_callbacks, :on_unsubscribe_callbacks, :periodic_timers, :instance_reader => false
+
+ self.on_subscribe_callbacks = []
+ self.on_unsubscribe_callbacks = []
+ self.periodic_timers = []
+ end
+
+ module ClassMethods
+ def on_subscribe(*methods)
+ self.on_subscribe_callbacks += methods
+ end
+
+ def on_unsubscribe(*methods)
+ self.on_unsubscribe_callbacks += methods
+ end
+
+ def periodic_timer(method, every:)
+ self.periodic_timers += [ [ method, every: every ] ]
+ end
+ end
+
+ end
+
+ end
+end \ No newline at end of file