Skip to content

Instantly share code, notes, and snippets.

@david-pm
Created December 7, 2018 20:59
Show Gist options
  • Save david-pm/635131c55dd22249803bdfbe30b4e5fb to your computer and use it in GitHub Desktop.
Save david-pm/635131c55dd22249803bdfbe30b4e5fb to your computer and use it in GitHub Desktop.
chat app demo code snippets
> rails g controller home index
> rails g channel chat
-------
config/routes.rb:
-------
root 'home#index'
-------
app/views/home/index.html.erb:
-------
Chat:
<br>
<span id='chat'></span>
<hr>
Message:
<br>
<textarea id='msg'></textarea>
<hr>
<button id='send'>Send Message</button>
<script>
document.addEventListener("DOMContentLoaded", function(){
const msg = document.getElementById('msg')
const chat = document.getElementById('chat')
const send = document.getElementById('send')
// overrides received method in chat.js
App.chat.received = function(data) {
chat.append(data['message'])
chat.appendChild(document.createElement('br'))
}
send.addEventListener('click', function(){
App.chat.speak(msg.value)
msg.value = ''
msg.focus()
});
});
</script>
-------
app/assets/javascripts/channels/chat.js
-------
App.chat = App.cable.subscriptions.create("ChatChannel", {
...
speak: function(data) {
return this.perform('speak', { message: data })
}
});
-------
app/channels/chat_channel.rb
-------
def subscribed
stream_from "some_channel"
end
...
def speak(data)
ActionCable.server.broadcast 'some_channel', message: data['message']
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment