Module: Tramway::Chats::Broadcast

Defined in:
lib/tramway/chats/broadcast.rb

Overview

This module provides a method to broadcast new chat messages to a Tramway Chat

Constant Summary collapse

MESSAGE_TYPES =
%i[sent received].freeze

Instance Method Summary collapse

Instance Method Details

#tramway_chat_append_message(chat_id:, type:, text:, sent_at:) ⇒ Object

Raises:

  • (ArgumentError)


9
10
11
12
13
14
15
16
# File 'lib/tramway/chats/broadcast.rb', line 9

def tramway_chat_append_message(chat_id:, type:, text:, sent_at:)
  raise ArgumentError, 'message_type must be :sent or :received' unless MESSAGE_TYPES.include?(type.to_sym)

  Turbo::StreamsChannel.broadcast_append_to [chat_id, 'messages'],
                                            target: 'messages',
                                            partial: 'tramway/chats/message',
                                            locals: { type:, text:, sent_at: }
end

#tramway_chat_append_messages(chat_id:, messages:) ⇒ Object



27
28
29
30
31
32
33
34
35
36
37
38
39
# File 'lib/tramway/chats/broadcast.rb', line 27

def tramway_chat_append_messages(chat_id:, messages:)
  messages.each do |message|
    unless MESSAGE_TYPES.include?(message[:type].to_sym)
      raise ArgumentError,
            'Each message must have :id and :type keys'
    end
  end

  Turbo::StreamsChannel.broadcast_append_to [chat_id, 'messages'],
                                            target: 'messages',
                                            partial: 'tramway/chats/messages',
                                            locals: { messages: }
end

#tramway_chat_prepend_message(chat_id:, type:, text:, sent_at:) ⇒ Object

Raises:

  • (ArgumentError)


18
19
20
21
22
23
24
25
# File 'lib/tramway/chats/broadcast.rb', line 18

def tramway_chat_prepend_message(chat_id:, type:, text:, sent_at:)
  raise ArgumentError, 'message_type must be :sent or :received' unless MESSAGE_TYPES.include?(type.to_sym)

  Turbo::StreamsChannel.broadcast_prepend_to [chat_id, 'messages'],
                                             target: 'messages',
                                             partial: 'tramway/chats/message',
                                             locals: { type:, text:, sent_at: }
end

#tramway_chat_prepend_messages(chat_id:, messages:) ⇒ Object



41
42
43
44
45
46
47
48
49
50
51
52
53
# File 'lib/tramway/chats/broadcast.rb', line 41

def tramway_chat_prepend_messages(chat_id:, messages:)
  messages.each do |message|
    unless MESSAGE_TYPES.include?(message[:type].to_sym)
      raise ArgumentError,
            'Each message must have :id and :type keys'
    end
  end

  Turbo::StreamsChannel.broadcast_prepend_to [chat_id, 'messages'],
                                             target: 'messages',
                                             partial: 'tramway/chats/messages',
                                             locals: { messages: }
end