Skip to content

Instantly share code, notes, and snippets.

@louisscruz
Last active February 19, 2018 04:30
Show Gist options
  • Save louisscruz/353429252f6a888262117e3d856ebfc2 to your computer and use it in GitHub Desktop.
Save louisscruz/353429252f6a888262117e3d856ebfc2 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));
}
});
}
}
@jsonreeder
Copy link

FYI it looks like there's a typo here:
Reach should be React

@drstonebraker
Copy link

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