cable icon indicating copy to clipboard operation
cable copied to clipboard

Some way to use Channel params/data

Open confact opened this issue 4 years ago • 1 comments

I have an issue that I want to trigger updates best on filters I have sent in as params in the channel.

Sending it in and set all that up as variables worked fine, but I can't find a way to access those to trigger updates.

So what I want to do is:

  1. set up a method in my channel that getting all the data and either call broadcast_to or return the data to send if needed
  2. call it in from the server, like Cable::Server.call_method_on_channel("TurboChannel") or something that calls the method in the channel

I was looking at the action part of it, but I DON'T want to send it to the frontend/through WebSocket. I want to trigger a method, that uses a variable on channels to send that data to that channel. As every channel has different filters/params.

Right now I set the variables in my channel in subscribe like this:

      temp_day_from = params["day_from"]?.to_s
      @day_from = Time.parse_utc(temp_day_from, "%F").at_beginning_of_day unless temp_day_from.nil?

      if !day_from.nil? && !params["domain_id"]?.nil?
        domain_id = params["domain_id"]?.to_s.to_i64
        @domain = DomainQuery.find(domain_id)
        @metrics = CurrentMetrics.new(@domain.not_nil!, day_from.not_nil!) unless @domain.nil?
      end

And I added an method that I am testing to update the data based on those data:

   def broadcast_metric_update
     return if @domain.nil? || @metrics.nil?
     puts "i update"
     Turbo::StreamsChannel.broadcast_update_to(@domain.not_nil!.address, "current_users", CurrentUserComponent.new(current_users: @metrics.not_nil!.current_users).render_to_string)
     #broadcast_update_to(@domain.address, "current_users", CurrentUserComponent.new(current_users: @metrics.current_users).render_to_string)
   end

confact avatar Mar 22 '21 20:03 confact

I'm not sure if I follow this correctly, but could you do something like this?

class SomeChannel < ApplicationCable::Channel
  def perform(action, data)
    case action
    when "broadcast_metric_update"
      temp_day_from = data["day_from"]?.to_s
      # ... other stuff
      Turbo::StreamsChannel.broadcast_update_to(data)
    end
  end
end

I was just going through issues and didn't see replies to this thread. Maybe no longer relevant?

jwoertink avatar Apr 20 '23 18:04 jwoertink