identification.rb 1.4 KB
Newer Older
1 2
require 'set'

3 4
module ActionCable
  module Connection
5 6 7 8 9 10 11 12 13
    module Identification
      extend ActiveSupport::Concern

      included do
        class_attribute :identifiers
        self.identifiers = Set.new
      end

      class_methods do
D
DAVID MOORE 已提交
14
        # Mark a key as being a connection identifier index that can then be used to find the specific connection again later.
15
        # Common identifiers are current_user and current_account, but could be anything, really.
16 17 18
        #
        # Note that anything marked as an identifier will automatically create a delegate by the same name on any
        # channel instances created off the connection.
19
        def identified_by(*identifiers)
20
          Array(identifiers).each { |identifier| attr_accessor identifier }
21
          self.identifiers += identifiers
22
        end
23 24
      end

25
      # Return a single connection identifier that combines the value of all the registered identifiers into a single gid.
26
      def connection_identifier
J
Jeremy Daer 已提交
27
        unless defined? @connection_identifier
28 29 30 31
          @connection_identifier = connection_gid identifiers.map { |id| instance_variable_get("@#{id}") }.compact
        end

        @connection_identifier
32 33
      end

34 35
      private
        def connection_gid(ids)
36
          ids.map do |o|
37 38
            if o.respond_to? :to_gid_param
              o.to_gid_param
39 40 41 42
            else
              o.to_s
            end
          end.sort.join(":")
43
        end
44 45 46
    end
  end
end