Last active
February 19, 2018 04:30
-
-
Save louisscruz/353429252f6a888262117e3d856ebfc2 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)); | |
} | |
}); | |
} | |
} |
Deploying on heroku requires additional configuration... see https://blog.heroku.com/real_time_rails_implementing_websockets_in_rails_5_with_action_cable
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
FYI it looks like there's a typo here:
Reach
should beReact