Last active
August 29, 2015 14:12
-
-
Save guilleiguaran/40811fc5a4c4577e45c0 to your computer and use it in GitHub Desktop.
Phoenix-like channels in Rails, adapted from: http://www.chrismccord.com/blog/2014/05/06/how-to-build-an-elixir-chat-app-with-phoenix/
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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" |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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(""); | |
} | |
}); | |
}); |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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