Skip to content

Instantly share code, notes, and snippets.

@jpbalarini
Created June 19, 2019 14:31
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save jpbalarini/253275f97fdeac960c11720959d37da1 to your computer and use it in GitHub Desktop.
Save jpbalarini/253275f97fdeac960c11720959d37da1 to your computer and use it in GitHub Desktop.
How to execute a method on rails via action cable
socket = new WebSocket('ws://localhost:3000/api/v1/action_cable');
const onMessage = (ws, store) => evt => {
let msg = JSON.parse(evt.data);
if (msg.type === "ping") {
return;
}
console.log("FROM RAILS: ", msg);
}
socket.onmessage = onMessage(socket);
// you need to subscribe to the channel first
var msg = {
command: 'subscribe',
identifier: JSON.stringify({
channel: 'ReadingsChannel',
}),
};
socket.send(JSON.stringify(msg));
// the method foobar is going to be executed on Rails (channel file)
var msg = {
command: 'message',
identifier: JSON.stringify({
channel: 'ReadingsChannel',
}),
data: JSON.stringify({
action: 'foobar',
code: 1234
}),
};
socket.send(JSON.stringify(msg));
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment