Class: Ki::ChannelManager

Inherits:
Object
  • Object
show all
Defined in:
lib/ki/channel_manager.rb

Class Method Summary collapse

Class Method Details

.cleanupObject



48
49
50
51
52
# File 'lib/ki/channel_manager.rb', line 48

def self.cleanup
  db.delete 'realtime_channel_sockets', {}
  db.delete 'realtime_channel_subscriptions', {}
  db.delete 'realtime_channel_messages', {}
end

.connectObject



3
4
5
# File 'lib/ki/channel_manager.rb', line 3

def self.connect
  db.insert 'realtime_channel_sockets', {}
end

.dbObject



54
55
56
# File 'lib/ki/channel_manager.rb', line 54

def self.db
  Orm::Db.instance
end

.disconnect(socket) ⇒ Object



7
8
9
10
# File 'lib/ki/channel_manager.rb', line 7

def self.disconnect(socket)
  db.delete 'realtime_channel_sockets', { 'id' => socket['id'] }
  db.delete 'realtime_channel_subscriptions', { 'socket_id' => socket['id'] }
end

.publish(json) ⇒ Object



30
31
32
33
# File 'lib/ki/channel_manager.rb', line 30

def self.publish(json)
  json['created_at'] = Time.now.to_i
  db.insert 'realtime_channel_messages', json
end

.socketsObject



12
13
14
# File 'lib/ki/channel_manager.rb', line 12

def self.sockets
  db.find 'realtime_channel_sockets'
end

.subscribe(json) ⇒ Object



16
17
18
19
20
21
22
23
# File 'lib/ki/channel_manager.rb', line 16

def self.subscribe(json)
  channels = db.find 'realtime_channel_subscriptions', json
  if channels.empty?
    item = db.insert 'realtime_channel_subscriptions', json
    channels.push item
  end
  channels
end

.tick(json) ⇒ Object



35
36
37
38
39
40
41
42
43
44
45
46
# File 'lib/ki/channel_manager.rb', line 35

def self.tick(json)
  subscribed_channels = db.find 'realtime_channel_subscriptions', json
  channel_names = subscribed_channels.map { |sc| sc['channel_name'] }

  t = Time.now.to_i

  messages = db.find 'realtime_channel_messages', {
    'channel_name' => { '$in' => channel_names },
    'created_at' => { '$gt' => t - 5 }
  }
  messages
end

.unsubscribe(json) ⇒ Object



25
26
27
28
# File 'lib/ki/channel_manager.rb', line 25

def self.unsubscribe(json)
  json.delete('type')
  db.delete 'realtime_channel_subscriptions', json
end