Hotwire broadcasting (Turbo streams)
Rails
hotwire
turbo
Turbo::StreamsChannel.broadcast_update_to
NOTE Alternative way https://hhh.how/notes/2141-hotwire-replace-content-with-stream-without-socket
How broadcasting streams work in Hotwire (Turbo streams Rails )
# app/views/pages/wherever.html.erb <% model = Model.last %> <%= turbo_stream_from model, :some_stream_identification %> <div id="viking_death_machine">Change me</div>
#app/jobs/me_updating_page_content_job.rb Model.new.broadcast_update_to( model, :some_stream_identification, target: "viking_death_machine", partial: "dashboard/awesome_stuff/my_partial", locals: {whatever: "anything you want to pass to partial"})
# app/views/dashboard/awesome_stuff/_my_partial.html.erb <strong><%= whatever %></strong>
realistically you want something more useful:
# app/views/pages/wherever.html.erb <% model = Model.last %> <%= turbo_stream_from model, :list_inputs %> <div id="<%= dom_id(model, :list_inputs) %>">Prepend to me</div>
include ActionView::RecordIdentifier model.broadcast_prepend_to( model.user, :list_inputs, target: dom_id(model, :list_inputs), partial: "dashboard/klaviyo_groups/list_option", locals: {model: model})
you can also broadcast later
broadcast_prepend_later_to broadcast_update_later_to ...
another example
<%= turbo_stream_from :some_stream_identification %> <div id="id_of_element_to_replace_content"></div>
you can execute this from rails console
ApplicationRecord.new.broadcast_update_to( :some_stream_identification, target: "id_of_element_to_replace_content", partial: "users/any_partial", locals: {whatever: "anything you want to pass to partial"})
Different ways to bradcast
e.g this can be invoked from Job/Sidekiq worker
model.broadcast_update_to(user, :messages, target: "message-count", html: "<p> #{user.messages.count} </p>") model.broadcast_replace_to(user, :message, target: "message", template: "messages/show", locals: { message: self })