Class: Slanger::Channel

Inherits:
Object
  • Object
show all
Extended by:
Forwardable
Includes:
Glamazon::Base
Defined in:
lib/slanger/channel.rb

Direct Known Subclasses

PresenceChannel

Class Method Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(attrs) ⇒ Channel

Returns a new instance of Channel.



34
35
36
37
# File 'lib/slanger/channel.rb', line 34

def initialize(attrs)
  super
  Slanger::Redis.subscribe channel_id
end

Class Method Details

.from(channel_id) ⇒ Object



20
21
22
23
# File 'lib/slanger/channel.rb', line 20

def from channel_id
  klass = channel_id[/^presence-/] ? PresenceChannel : Channel
  klass.find_or_create_by_channel_id channel_id
end

.send_client_message(msg) ⇒ Object



29
30
31
# File 'lib/slanger/channel.rb', line 29

def send_client_message msg
  from(msg['channel']).try :send_client_message, msg
end

.unsubscribe(channel_id, subscription_id) ⇒ Object



25
26
27
# File 'lib/slanger/channel.rb', line 25

def unsubscribe channel_id, subscription_id
  from(channel_id).try :unsubscribe, subscription_id
end

Instance Method Details

#authenticated?Boolean

Returns:

  • (Boolean)


75
76
77
# File 'lib/slanger/channel.rb', line 75

def authenticated?
  channel_id =~ /^private-/ || channel_id =~ /^presence-/
end

#channelObject



39
40
41
# File 'lib/slanger/channel.rb', line 39

def channel
  @channel ||= EM::Channel.new
end

#dispatch(message, channel) ⇒ Object

Send an event received from Redis to the EventMachine channel which will send it to subscribed clients.



71
72
73
# File 'lib/slanger/channel.rb', line 71

def dispatch(message, channel)
  push(message.to_json) unless channel =~ /^slanger:/
end

#send_client_message(message) ⇒ Object

Send a client event to the EventMachine channel. Only events to channels requiring authentication (private or presence) are accepted. Public channels only get events from the API.



65
66
67
# File 'lib/slanger/channel.rb', line 65

def send_client_message(message)
  Slanger::Redis.publish(message['channel'], message.to_json) if authenticated?
end

#subscribe(*a, &blk) ⇒ Object



43
44
45
46
47
48
49
50
# File 'lib/slanger/channel.rb', line 43

def subscribe *a, &blk
  Slanger::Redis.hincrby('channel_subscriber_count', channel_id, 1).
    callback do |value|
      Slanger::Webhook.post name: 'channel_occupied', channel: channel_id if value == 1
    end

  channel.subscribe *a, &blk
end

#unsubscribe(*a, &blk) ⇒ Object



52
53
54
55
56
57
58
59
# File 'lib/slanger/channel.rb', line 52

def unsubscribe *a, &blk
  Slanger::Redis.hincrby('channel_subscriber_count', channel_id, -1).
    callback do |value|
      Slanger::Webhook.post name: 'channel_vacated', channel: channel_id if value == 0
    end

  channel.unsubscribe *a, &blk
end