0

my channel:

class DevicesChannel < ApplicationCable::Channel
  def subscribed
    stream_from 'datas_channel', coder: ActiveSupport::JSON
  end

  def unsubscribed
    # Any cleanup needed when channel is unsubscribed
    raise NotImplementedError
  end

  def receive
    data = DeviceInformation.create(message: "oks")
    ActionCable.server.broadcast("datas_channel", data)
  end
end

To send request for subscribe, did:

{
  "command": "subscribe",
  "identifier": "{\"channel\":\"DevicesChannel\"}"
}

And, to write message:

{
    "command": "message",
    "identifier": "{\"channel\":\"DevicesChannel\"}",
    "data": "{\"message\":\"Hello world\", \"action\": \"receive\"}"
}

On above request, it works well. it call receive method and works well.

But i want to call controller action 'Create' i.e

class DeviceInformationsController < ApplicationController
  def create
    data = DeviceInformation.create(message: 'Hello world')
    ActionCable.server.broadcast("datas_channel", data)
  end
end

is it possible to do? any help would be really appreciated. I am new to web socket API

Rasna Shakya
  • 527
  • 2
  • 13
  • Why d you want to do that? can you create a method inside model to directly use it inside controller and channel so that you can achieve same functionality in both controller and channel? – Gagan Gupta Mar 15 '21 at 18:12
  • i just want to make sure, is it possible to do so or not? – Rasna Shakya Mar 15 '21 at 18:16
  • You will run into some errors if there's any auth or session related logic in your controllers (In most cases there will be) and you can read this post for more clarity :) https://stackoverflow.com/questions/42451889/how-do-i-get-current-user-in-actioncable-rails-5-api-app/42452474#42452474 – Gagan Gupta Mar 15 '21 at 18:24

1 Answers1

0

You can follow the way Rails-core do integration testing: https://github.com/rails/rails/blob/main/actionpack/lib/action_dispatch/testing/integration.rb (read the code ActionDispatch::Integration::Session#process)

I did a demo (get all targets - TargetsController#index)

class DevChannel < ApplicationCable::Channel
  # ...
  def receive(data)
    session = ActionDispatch::Integration::Session.new(Rails.application)
    path = ENV.fetch("APPLICATION_HOST") + Rails.application.routes.url_helpers.targets_path
    session.get(path)
    ActionCable.server.broadcast("DevChannel", session.response.body)
  end
end
Lam Phan
  • 3,405
  • 2
  • 9
  • 20