0

I am implementing with ActionCable a chat inside my game room (game). Here is my code so far:

app/channels/game_channel.rb:

class GameChannel < ApplicationCable::Channel
  def subscribed
    stream_from "game_channel_#{params[:game]}" 
  end

  def unsubscribed
    # Any cleanup needed when channel is unsubscribed
  end

  def speak (data)
     ActionCable.server.broadcast("game_channel_#{params[:game]}", data) 
  end
end

app/assets/javascripts/channels/game.js.erb:

<% Game.all.each do |game| %>  

  App['game' + <%=game.id%>] = App.cable.subscriptions.create({channel: 'GameChannel', game: <%= game.id %>}, {  
  received: function(data) {
   alert(message)
   },

  setGameId: function(gameId) {
    this.gameId = gameId
  },
  
  speak: function(data) {
    this.perform('speak'), message => data['message']
    }
});
<% end %>

When I send the commands:

App.game1.speak (message: "Test1", player: 1, game:1)

--> Alerts Msg:"Test1" @ Game 1.

App.game2.speak (message: "Hello", player: 2, game:2) 

--> Alerts Msg "Hello" @ Game 2, AND @ Game 1 it alerts the msg: "Test1" again.

How to fix this, only showing the message @ the updated game, without updating at others game's room?

Server is displaying:

17:03:01 web.1  | GameChannel is transmitting the subscription confirmation
17:03:01 web.1  | GameChannel is streaming from game_channel_2
17:03:01 web.1  | GameChannel is transmitting the subscription confirmation
17:03:01 web.1  | GameChannel is streaming from game_channel_1
17:03:06 web.1  | GameChannel#speak
17:03:06 web.1  | [ActionCable] Broadcasting to game_channel_1: {"action"=>"speak"}
17:03:06 web.1  | GameChannel transmitting {"action"=>"speak"} (via streamed from game_channel_1)
17:03:06 web.1  | GameChannel transmitting {"action"=>"speak"} (via streamed from game_channel_1)
17:03:11 web.1  | GameChannel#speak
17:03:11 web.1  | [ActionCable] Broadcasting to game_channel_2: {"action"=>"speak"}
17:03:11 web.1  | GameChannel transmitting {"action"=>"speak"} (via streamed from game_channel_2)
17:03:11 web.1  | GameChannel transmitting {"action"=>"speak"} (via streamed from game_channel_2)
Community
  • 1
  • 1
Felipe Maion
  • 336
  • 1
  • 12

1 Answers1

0

Here is my solution (I don't know, but it doesn't seem right), any comments? I added to my game.js.erb the following conditional:

<% Game.all.each do |game| %>  
  App['game' + <%= game.id %>] = App.cable.subscriptions.create({channel: 'GameChannel', game: <%= game.id %>}, {  
  received: function(data) {
  if (game == <%= game.id %>) {
  alert ('message: ' + message + '; game: ' + <%= game.id %> + '; game: ' + game);
      }},

  setGameId: function(gameId) {
    this.gameId = gameId
  },

  speak: function(data) {
    this.perform('speak')
    }
});
<% end %>

Basically I am comparing the game sent with the game room id.

Felipe Maion
  • 336
  • 1
  • 12