-
-
Save CelesteComet/7005525c0239f6bcab45d56213db38e7 to your computer and use it in GitHub Desktop.
ActionCable
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 ChannelChannel < ApplicationCable::Channel | |
def subscribed | |
stream_from "channel_#{params[:channel_name]}" | |
end | |
end |
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 Message < ApplicationRecord | |
after_commit { MessageRelayJob.perform_later(self, self.channel) } | |
#... | |
end |
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 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 |
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 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