Search code examples
ruby-on-railswebsocketjobsruby-on-rails-5actioncable

Where do Rails Jobs get called from in ActionCable and how can you pass parameters?


For example where is the the perform method originally getting called in this following job in:

jobs/message_broadcast_job.rb

class MessageBroadcastJob < ApplicationJob
  queue_as :default

  def perform(message)
    ActionCable.server.broadcast "room_channel", message: render_message(message) #, roomId: roomId
  end

  private
    def render_message(message)
      ApplicationController.renderer.render(partial: 'messages/message', locals: { message: message })
    end
end

In assets/javascripts/channels/room.coffee there is a method call:

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

But that seems to call the corresponding method in channels/room_channel.rb:

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

So where is the job getting called from, and how can I pass parameters into it? (Specifically I have a room channel ID I've already passed to room_channel.rb via parameters, but also need to get this in the perform action to broadcast from the relevant room channel.

Thanks!


Solution

  • In the model, models/message.rb

    after_create_commit { MessageBroadcastJob.perform_later self }
    

    Puts the job into the queue after the creation of the message. Therefore, in the job file you can access parameters via the object itself, in this case the message.

    Specifically, in this case it would be:

     def perform(message)
        ActionCable.server.broadcast "room_channel_#{message.room_id}", message: render_message(message) #, roomId: roomId
      end
    

    As all of the attributes for message are available.