Skip to content

Instantly share code, notes, and snippets.

@jwoertink
Created January 24, 2021 00:24
Show Gist options
  • Save jwoertink/0ede029c9647a26d6ad3c305de320c58 to your computer and use it in GitHub Desktop.
Save jwoertink/0ede029c9647a26d6ad3c305de320c58 to your computer and use it in GitHub Desktop.
# in src/app_server.cr
def middleware : Array(HTTP::Handler)
[
Lucky::ForceSSLHandler.new,
Lucky::HttpMethodOverrideHandler.new,
Lucky::LogHandler.new,
Lucky::ErrorHandler.new(action: Errors::Show),
CORSHandler.new,
Lucky::RemoteIpHandler.new,
Cable::Handler.new(ApplicationCable::Connection),
Lucky::RouteHandler.new,
Lucky::StaticCompressionHandler.new("./public", file_ext: "gz", content_encoding: "gzip"),
Lucky::StaticFileHandler.new("./public", fallthrough: false, directory_listing: false),
Lucky::RouteNotFoundHandler.new,
] of HTTP::Handler
end
# in config/cable.cr
# This is all just default anyway
Cable.configure do |settings|
settings.route = "/cable" # the URL your JS Client will connect
settings.token = "token" # The query string parameter used to get the token
end
// in src/js/components/chat.vue
channels: {
streamer_chat_room: {
received(data) {
this.messageReceived(data);
},
},
},
mounted() {
this.$cable.connection.connect();
this.$cable.subscribe(
{
channel: "ChatChannel",
stream_id: this.streamer.slug,
},
"streamer_chat_room"
);
},
beforeDestroy() {
this.$cable.unsubscribe("streamer_chat_room");
this.$cable.connection.disconnect();
},
destroyed() {
this.$cable.connection.disconnect();
// Actually disconnect from the server
// https://github.com/mclintprojects/actioncable-vue/blob/85b0d4fd1970131da307f6b9b35a1f2cc2e75b94/src/mixin.js#L35
if (this.$options.channels || this.channels) {
const channels = this.channels || this.$options.channels;
const entries = Object.entries(channels);
for (let index = 0; index < entries.length; index++) {
const entry = entries[index];
if (entry[0] != "computed")
this.$cable._removeChannel(entry[0], this._uid);
else {
const computedChannels = entry[1];
computedChannels.forEach((channel) => {
const channelName = channel.channelName.call(this);
this.$cable._removeChannel(channelName, this._uid);
});
}
}
}
},
# in src/channels/chat_channel.cr
class ChatChannel < ApplicationCable::Channel
def subscribed
stream_from("chat:#{params["stream_id"]}")
end
def perform(action, data)
# save chat message
end
end
// in src/js/channels/consumer.js
import { createConsumer } from "@rails/actioncable";
const wsEndpoint = process.env.MIX_WS_ENDPOINT;
export default createConsumer(wsEndpoint);
// These are the main packages I'm using
// "@rails/actioncable": "^6.0.3-4",
// "vue": "^2.6.12",
// "actioncable-vue": "^2.4.0",
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment