aboutsummaryrefslogtreecommitdiffstats
path: root/lib/action_cable/channel/base.rb
diff options
context:
space:
mode:
authorPratik Naik <pratiknaik@gmail.com>2015-01-14 21:59:31 +0530
committerPratik Naik <pratiknaik@gmail.com>2015-01-14 21:59:47 +0530
commitdb568553d172e6ebdc3bc0aae3839d4a91299b42 (patch)
treec3c24d67395a2d0e4224697c8809e2200d2e62ce /lib/action_cable/channel/base.rb
downloadrails-db568553d172e6ebdc3bc0aae3839d4a91299b42.tar.gz
rails-db568553d172e6ebdc3bc0aae3839d4a91299b42.tar.bz2
rails-db568553d172e6ebdc3bc0aae3839d4a91299b42.zip
Action Cable take#1
Diffstat (limited to 'lib/action_cable/channel/base.rb')
-rw-r--r--lib/action_cable/channel/base.rb64
1 files changed, 64 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