-
Notifications
You must be signed in to change notification settings - Fork 31
/
chat_reflex.rb
41 lines (32 loc) · 1.1 KB
/
chat_reflex.rb
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
37
38
39
40
41
# frozen_string_literal: true
class ChatReflex < ApplicationReflex
include ActionView::Helpers::SanitizeHelper
def post(color, message)
morph :nothing
message = strip_tags(message[0, 100])
return if message.blank?
chat = {
color: color,
author: request.remote_ip,
message: message,
created_at: Time.current.iso8601
}
chat_html = ChatsController.render(partial: "chats/chat", locals: {chat: chat, color: color})
list_selector = "##{color} [data-target='chat.list']"
input_selector = "##{color} textarea"
# broadcast to the user that triggered the reflex
cable_ready.set_value(selector: input_selector, value: "", focus_selector: input_selector).broadcast
# global broadcast to everyone
cable_ready["chat"]
.insert_adjacent_html(selector: list_selector, html: chat_html)
.dispatch_event(name: "chats:added")
.broadcast
# persist data
chats = Rails.cache.read(:chats) || []
chats << chat
Rails.cache.write :chats, chats
end
def set_color
session[:chat_color] = element[:href].delete("#")
end
end