Skip to content

Instantly share code, notes, and snippets.

@CelesteComet
Forked from louisscruz/channel_channel.rb
Created January 21, 2018 18:53
Show Gist options
  • Save CelesteComet/7005525c0239f6bcab45d56213db38e7 to your computer and use it in GitHub Desktop.
Save CelesteComet/7005525c0239f6bcab45d56213db38e7 to your computer and use it in GitHub Desktop.
ActionCable
class ChannelChannel < ApplicationCable::Channel
def subscribed
stream_from "channel_#{params[:channel_name]}"
end
end
class Message < ApplicationRecord
after_commit { MessageRelayJob.perform_later(self, self.channel) }
#...
end
class MessageRelayJob < ApplicationJob
def perform(message, channel)
message = Api::MessagesController.render(
partial: 'api/messages/message',
locals: { message: message }
)
ActionCable.server.broadcast("channel_#{channel.name}",
message: JSON.parse(message))
end
end
//...
class Root extends React.Component {
//...
// create some kind of function that creates a socket connection (possibly delete all others) and run that function where needed (onEnter?)
setSocket(channelName) {
if (window.App.channel) {
this.removeSocket();
}
this.addSocket(channelName);
}
removeSocket() {
window.App.cable.subscriptions.remove(window.App.channel);
}
addSocket(channelName) {
window.App.channel = window.App.cable.subscriptions.create({
channel: 'ChannelChannel',
channel_name: channelName
}, {
connected: () => {},
disconnected: () => {},
received: (data) => {
this.props.store.dispatch(receiveMessage(data.message));
}
});
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment