aboutsummaryrefslogtreecommitdiffstats
path: root/actioncable/lib/action_cable/channel/broadcasting.rb
blob: bd900e1c6556d3dbf5b1e3f1d4c29b44fb340972 (plain) (blame)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
# frozen_string_literal: true

require "active_support/core_ext/object/to_param"

module ActionCable
  module Channel
    module Broadcasting
      extend ActiveSupport::Concern

      delegate :broadcasting_for, to: :class

      module ClassMethods
        # Broadcast a hash to a unique broadcasting for this <tt>model</tt> in this channel.
        def broadcast_to(model, message)
          ActionCable.server.broadcast(broadcasting_for(model), message)
        end

        # Returns a unique broadcasting identifier for this <tt>model</tt> in this channel.
        def broadcasting_for(model)
          serialize_broadcasting([ channel_name, model ])
        end

        def serialize_broadcasting(object) #:nodoc:
          case
          when object.is_a?(Array)
            object.map { |m| serialize_broadcasting(m) }.join(":")
          when object.respond_to?(:to_gid_param)
            object.to_gid_param
          else
            object.to_param
          end
        end
      end
    end
  end
end