What’re the differences between broadcasts
& broadcasts_to
?
For instance, when I use broadcasts in share.rb (The model file), I got:
[ActionCable] Broadcasting to Z2lkOi8vbWluaS1zdG9ja21hcmtldC9TaGFyZS81: …
When I use broadcasts_to → (anythingHere) {‘shares’}, I got:
Broadcasting to shares: …
Why?
I do my best to explain the differences and inherent possibilities of stream_for
/broadcast_to
in the Broadcasting to Resources chapter of the CableReady docs.
Deep down, broadcasting to a resource identifier is the exact same thing as broadcasting to a string identifier. The magic is in the conceptual notion that you’re broadcasting to every client that currently has a given resource in scope. Instead of broadcast_to Post.find(1)
you could broadcast at posts:1
, but that’s not nearly as elegant.
1 Like
I think what was confusing here is why does broadcasts use a random hash instead of the plural name for the model you can find out why by tracing the rabbit trail and find this method
def stream_name_from(streamables)
if streamables.is_a?(Array)
streamables.map { |streamable| stream_name_from(streamable) }.join(":")
else
streamables.then { |streamable| streamable.try(:to_gid_param) || streamable.to_param }
end
end
by default it will pass the instance of the model as the streamables argument which will then result in it calling to_gid_param
which means when you say broadcasts
it will be broadcasting to the instance and not the plural name.
# Configures the model to broadcast creates, updates, and destroys to a stream name derived at runtime by the
# <tt>stream</tt> symbol invocation. By default, the creates are appended to a dom id target name derived from
# the model's plural name. The insertion can also be made to be a prepend by overwriting <tt>inserts_by</tt> and
# the target dom id overwritten by passing <tt>target</tt>. Examples:
#
# class Message < ApplicationRecord
# belongs_to :board
# broadcasts_to :board
# end
#
# class Message < ApplicationRecord
# belongs_to :board
# broadcasts_to ->(message) { [ message.board, :messages ] }, inserts_by: :prepend, target: "board_messages"
# end
def broadcasts_to(stream, inserts_by: :append, target: broadcast_target_default)
after_create_commit -> { broadcast_action_later_to stream.try(:call, self) || send(stream), action: inserts_by, target: target.try(:call, self) || target }
after_update_commit -> { broadcast_replace_later_to stream.try(:call, self) || send(stream) }
after_destroy_commit -> { broadcast_remove_to stream.try(:call, self) || send(stream) }
end
def broadcasts(inserts_by: :append, target: broadcast_target_default)
after_create_commit -> { broadcast_action_later action: inserts_by, target: target.try(:call, self) || target }
after_update_commit -> { broadcast_replace_later }
after_destroy_commit -> { broadcast_remove }
end