Module: Turbo::Train::Broadcastable::ClassMethods

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

Instance Method Summary collapse

Instance Method Details

#train_broadcast_target_defaultObject

All default targets will use the return of this method. Overwrite if you want something else than model_name.plural.



40
41
42
# File 'app/models/concerns/turbo/train/broadcastable.rb', line 40

def train_broadcast_target_default
  model_name.plural
end

#train_broadcasts(stream = model_name.plural, inserts_by: :append, target: train_broadcast_target_default, **rendering) ⇒ Object

Same as #train_broadcasts_to, but the designated stream for updates and destroys is automatically set to the current model, for creates - to the model plural name, which can be overriden by passing stream.



33
34
35
36
37
# File 'app/models/concerns/turbo/train/broadcastable.rb', line 33

def train_broadcasts(stream = model_name.plural, inserts_by: :append, target: train_broadcast_target_default, **rendering)
  after_create_commit  -> { train_broadcast_action_later_to(stream, action: inserts_by, target: target.try(:call, self) || target, **rendering) }
  after_update_commit  -> { train_broadcast_replace_later(**rendering) }
  after_destroy_commit -> { train_broadcast_remove }
end

#train_broadcasts_to(stream, inserts_by: :append, target: train_broadcast_target_default, **rendering) ⇒ 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 inserts_by 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
  train_broadcasts_to ->(message) { [ message.board, :messages ] }, inserts_by: :prepend, target: "board_messages"
end

class Message < ApplicationRecord
  belongs_to :board
  train_broadcasts_to ->(message) { [ message.board, :messages ] }, partial: "messages/custom_message"
end


25
26
27
28
29
# File 'app/models/concerns/turbo/train/broadcastable.rb', line 25

def train_broadcasts_to(stream, inserts_by: :append, target: train_broadcast_target_default, **rendering)
  after_create_commit  -> { train_broadcast_action_later_to(stream.try(:call, self) || send(stream), action: inserts_by, target: target.try(:call, self) || target, **rendering) }
  after_update_commit  -> { train_broadcast_replace_later_to(stream.try(:call, self) || send(stream), **rendering) }
  after_destroy_commit -> { train_broadcast_remove_to(stream.try(:call, self) || send(stream)) }
end