Skip to content

Instantly share code, notes, and snippets.

@ntamvl
Created March 22, 2018 04:10
Show Gist options
  • Save ntamvl/9d5f3adcbea8ea3cc7e39d59c11700c1 to your computer and use it in GitHub Desktop.
Save ntamvl/9d5f3adcbea8ea3cc7e39d59c11700c1 to your computer and use it in GitHub Desktop.
ActionCable: How to use dynamic channels

ActionCable: How to use dynamic channels

Pass a roomId on your subscription creation in javascripts/channels/room.js:

MakeMessageChannel = function(roomId) {
  // Create the new room channel subscription
  App.room = App.cable.subscriptions.create({
    channel: "RoomChannel",
    roomId: roomId
  }, {
    connected: function() {},
    disconnected: function() {},
    received: function(data) {
      return $('#messages').append(data['message']);
    },
    speak: function(message, roomId) {
      return this.perform('speak', {
        message: message,
        roomId: roomId
      });
    }
  });

  $(document).on('keypress', '[data-behavior~=room_speaker]', function(event) {
    if (event.keyCode === 13) {
      App.room.speak(event.target.value, roomId);
      event.target.value = "";
      event.preventDefault();
    }
    return $('#messages').animate({
      scrollTop: $('#messages')[0].scrollHeight
    }, 100);
  });
};

In channels/room_channel.rb it becomes available as a parameter for the subscription creation, and the speak action was also just called with the correct data:

def subscribed
  stream_from "room_channel_#{params[:roomId]}"
end

def speak(data)
   Message.create! text: data['message'], room_id: data['roomId']
end

And then if you're broadcasting from a job:

def perform(message)
  ActionCable.server.broadcast "room_channel_#{message.room_id}", message: render_message(message)
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment