Skip to content

Instantly share code, notes, and snippets.

@connorbey13
Last active July 8, 2022 22:17
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save connorbey13/f56d691ba192d29a933065dbb73bcb35 to your computer and use it in GitHub Desktop.
Save connorbey13/f56d691ba192d29a933065dbb73bcb35 to your computer and use it in GitHub Desktop.
turbo_custom_cable_stream
module ApplicationHelper
def turbo_custom_stream_from(*streamables, **attributes)
attributes[:channel] = attributes[:channel]&.to_s || "Turbo::StreamsChannel"
attributes[:"signed-stream-name"] = Turbo::StreamsChannel.signed_stream_name(streamables)
tag.turbo_custom_cable_stream_source(**attributes)
end
end
import { Turbo, cable } from "@hotwired/turbo-rails";
const { connectStreamSource, disconnectStreamSource } = Turbo;
const { subscribeTo } = cable;
class TurboCustomCableStreamSource extends HTMLElement {
async connectedCallback() {
connectStreamSource(this);
this.subscription = await subscribeTo(this.channel, {
initialized() {
},
connected() {
},
received(data) {
},
disconnected() {
},
received: this.dispatchMessageEvent.bind(this)
});
}
disconnectedCallback() {
disconnectStreamSource(this);
if (this.subscription) this.subscription.unsubscribe();
}
dispatchMessageEvent(data) {
const event = new MessageEvent("message", { data });
return this.dispatchEvent(event);
}
get channel() {
const channel = this.getAttribute("channel");
const signed_stream_name = this.getAttribute("signed-stream-name");
return { channel, signed_stream_name };
}
}
customElements.define("turbo-custom-cable-stream-source", TurboCustomCableStreamSource);
class CustomChannel < ActionCable::Channel::Base
extend Turbo::Streams::Broadcasts, Turbo::Streams::StreamName
include Turbo::Streams::StreamName::ClassMethods
def subscribed
if stream_name = verified_stream_name_from_params
stream_from stream_name
else
reject
end
end
def unsubscribed
end
end
<%= turbo_custom_stream_from "example", channel: CustomChannel %>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment