Hello I have a basic chat room set up on action cable and was wondering whether there was a way to give the current user a temporary username while posting in the chat room? preferably set up so they have to type their username In before they are allowed to chat?
Here the code I have:
this is the view:
<h1>Chat room</h1>
<div id="messages">
<%= render @messages %>
</div>
<form>
<label>Say something:</label><br>
<input type="text" data-behavior="room_speaker">
</form>
this is the room channel:
class RoomChannel < ApplicationCable::Channel
def subscribed
stream_from "room_channel"
end
def unsubscribed
# Any cleanup needed when channel is unsubscribed
end
def speak(data)
Message.create! content: data['message']
end
end
the message broadcast job:
class MessageBroadcastJob < ApplicationJob
queue_as :default
def perform(message)
ActionCable.server.broadcast 'room_channel', message: render_message(message)
end
private
def render_message(message)
ApplicationController.renderer.render(partial: 'messages/message', locals: { message: message })
end
end
and the coffee script:
App.room = App.cable.subscriptions.create "RoomChannel",
connected: ->
# Called when the subscription is ready for use on the server
disconnected: ->
# Called when the subscription has been terminated by the server
received: (data) ->
$('#messages').append data['message']
speak: (message) ->
@perform 'speak' , message: message
$(document).on 'keypress', '[data-behavior~=room_speaker]', (event) ->
if event.keyCode is 13
App.room.speak event.target.value
event.target.value = ''
event.preventDefault();
here is my controller:
class RoomsController < ApplicationController
def index
@messages = Message.all
end
end
the page that I render:
<div class="message">
<p><%=message.content%></p>
</div>