Skip to content

Instantly share code, notes, and snippets.

@guilleiguaran
Last active August 29, 2015 14:12
Show Gist options
  • Save guilleiguaran/40811fc5a4c4577e45c0 to your computer and use it in GitHub Desktop.
Save guilleiguaran/40811fc5a4c4577e45c0 to your computer and use it in GitHub Desktop.
class ChatChannel < ActionChannel::Base
# join is triggered on user connect
def join(channel, message)
puts "JOIN #{channel}"
# reply messages are sent only to the user invoking the action
reply "user:welcome", salute: "Welcome to the channel #{message['username']}!!!"
# broadcast messages are sent to all the users connected to the channel
broadcast "user:entered", username: message["username"]
end
def new_message(message)
broadcast "new:message", content: message["content"], username: messages["username"]
end
# leave is triggered on user disconnect, by default we can provide a no-op method
# and allow to users to override it
def leave(channel, message)
broadcast "user:left", username: message["username"]
end
end
# Broadcast an outgoing message to this channel from a controller/model:
# ChatChannel.broadcast "new:message", content: "Hello from Rails controller", username: "ChanServer"
var socket = new ActionChannel("ws://" + location.host + "/ws");
var $messages = $("#messages");
var $messageInput = $("#message-input");
var $usernameInput = $("#username");
socket.join("chat", {}, function(chan){
chan.on("user:entered", function(message){
$messages.append("<br/>[" + message.username + "] entered")
});
chan.on("new:message", function(msg){
$messages.append("<br/>[" + msg.username + "] " + msg.content)
});
$messageInput.off("keypress").on("keypress", function(e){
if(e.keyCode == 13){
chan.send("new:message", {
content: $messageInput.val(),
username: $usernameInput.val()
});
$messageInput.val("");
}
});
});
ChatApp::Application.routes.draw do
socket "/ws" do
channel "chat"
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment