Class: ActionCable::Connection::Subscriptions

Inherits:
Object
  • Object
show all
Defined in:
lib/action_cable/connection/subscriptions.rb

Overview

# Action Cable Connection Subscriptions

Collection class for all the channel subscriptions established on a given connection. Responsible for routing incoming commands that arrive on the connection to the proper channel.

Defined Under Namespace

Classes: AlreadySubscribedError, ChannelNotFound, Error, MalformedCommandError, UnknownCommandError, UnknownSubscription

Instance Method Summary collapse

Constructor Details

#initialize(connection) ⇒ Subscriptions

Returns a new instance of Subscriptions.



47
48
49
50
# File 'lib/action_cable/connection/subscriptions.rb', line 47

def initialize(connection)
  @connection = connection
  @subscriptions = {}
end

Instance Method Details

#add(data) ⇒ Object



62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
# File 'lib/action_cable/connection/subscriptions.rb', line 62

def add(data)
  id_key = data["identifier"]

  raise MalformedCommandError, data unless id_key.present?

  raise AlreadySubscribedError, id_key if subscriptions.key?(id_key)

  subscription = subscription_from_identifier(id_key)

  if subscription
    subscriptions[id_key] = subscription
    subscription.subscribe_to_channel
  else
    id_options = ActiveSupport::JSON.decode(id_key).with_indifferent_access
    raise ChannelNotFound, id_options[:channel]
  end
end

#execute_command(data) ⇒ Object



52
53
54
55
56
57
58
59
60
# File 'lib/action_cable/connection/subscriptions.rb', line 52

def execute_command(data)
  case data["command"]
  when "subscribe"   then add data
  when "unsubscribe" then remove data
  when "message"     then perform_action data
  else
    raise UnknownCommandError, data["command"]
  end
end

#identifiersObject



94
95
96
# File 'lib/action_cable/connection/subscriptions.rb', line 94

def identifiers
  subscriptions.keys
end

#perform_action(data) ⇒ Object



90
91
92
# File 'lib/action_cable/connection/subscriptions.rb', line 90

def perform_action(data)
  find(data).perform_action ActiveSupport::JSON.decode(data["data"])
end

#remove(data) ⇒ Object



80
81
82
83
# File 'lib/action_cable/connection/subscriptions.rb', line 80

def remove(data)
  logger.info "Unsubscribing from channel: #{data['identifier']}"
  remove_subscription find(data)
end

#remove_subscription(subscription) ⇒ Object



85
86
87
88
# File 'lib/action_cable/connection/subscriptions.rb', line 85

def remove_subscription(subscription)
  subscription.unsubscribe_from_channel
  subscriptions.delete(subscription.identifier)
end

#unsubscribe_from_allObject



98
99
100
# File 'lib/action_cable/connection/subscriptions.rb', line 98

def unsubscribe_from_all
  subscriptions.each { |id, channel| remove_subscription(channel) }
end