Module: Turbo::Broadcastable::ClassMethods

Defined in:
app/models/concerns/turbo/broadcastable.rb

Instance Method Summary collapse

Instance Method Details

#broadcasts(inserts_by: :append, target: model_name.plural) ⇒ Object

Same as #broadcasts_to, but the designated stream is automatically set to the current model.


61
62
63
64
65
# File 'app/models/concerns/turbo/broadcastable.rb', line 61

def broadcasts(inserts_by: :append, target: model_name.plural)
  after_create_commit  -> { broadcast_action_later action: inserts_by, target: target }
  after_update_commit  -> { broadcast_replace_later }
  after_destroy_commit -> { broadcast_remove }
end

#broadcasts_to(stream, inserts_by: :append, target: model_name.plural) ⇒ Object

Configures the model to broadcast creates, updates, and destroys to a stream name derived at runtime by the stream 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 insertion and the target dom id overwritten by passing target. 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

54
55
56
57
58
# File 'app/models/concerns/turbo/broadcastable.rb', line 54

def broadcasts_to(stream, inserts_by: :append, target: model_name.plural)
  after_create_commit  -> { broadcast_action_later_to stream.try(:call, self) || send(stream), action: inserts_by, target: 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