6

I am new to ActionCable in Rails 5. I am trying to make a chat for my Rails app. When I try and send a test message through the console App.room.speak('Test!') but when I do I get an error.

Uncaught ReferenceError: App is not defined at :1:1

room.coffe

App.room = App.cable.subscriptions.create "RoomChannel",
  connected: ->
  # Called when the subscription is ready for use on the server

  disconnected: ->
  # Called when the subscription has been terminated by the server

  received: (data) ->
  # Called when there's incoming data on the websocket for this channel
  $('message').append data

  speak: (message)->
  @perform 'speak', message: message

room_channel.rb

class RoomChannel < ApplicationCable::Channel
   def subscribed
     stream_from "room_channel"
   end

   def unsubscribed
      # Any cleanup needed when channel is unsubscribed
   end

   def speak (data)
     Message.new content: data['message'], user: current_user
   end
end

broadcast_message_job.rb

class BroadcastMessageJobJob < ApplicationJob
   queue_as :default

   def perform(meesage)
     ActionCable.server.broadcast 'room_channel', render_message(message)
   end

   private

   def render_message(message)
     ApplicationController.renderer.render message
   end
end

cable.js

(function() {
   this.App || (this.App = {});

   App.cable = ActionCable.createConsumer();

}).call(this);

routes.rb

mount ActionCable.server => '/cable'
Sebastián Palma
  • 32,692
  • 6
  • 40
  • 59
jrocc
  • 1,274
  • 2
  • 18
  • 48

1 Answers1

3

Make sure you've added the require_self in the cable.js file:

// app/assets/javascripts/cable.js
//= require action_cable
//= require_self
//= require_tree ./channels

(function() {
  this.App || (this.App = {});
  App.cable = ActionCable.createConsumer();
}).call(this);

This will add the content from this same cable.js file, if you've defined the App in other file, then you'll need to add it in the "require" section.

Sebastián Palma
  • 32,692
  • 6
  • 40
  • 59
  • 1
    Does js file load order matter when it comes defining `App`? If the same anonymous function was in another file then wouldn't it have the same result of either using `this.App` if it's already been declared or otherwise set it to an empty object and begin using it? – Marklar Apr 10 '18 at 06:28