Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Turbo::Broadcastable#broadcasts broadcasts creates to model_name.plural stream #295

Merged
merged 1 commit into from
May 22, 2022
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
7 changes: 4 additions & 3 deletions app/models/concerns/turbo/broadcastable.rb
Original file line number Diff line number Diff line change
Expand Up @@ -71,9 +71,10 @@ def broadcasts_to(stream, inserts_by: :append, target: broadcast_target_default)
after_destroy_commit -> { broadcast_remove_to stream.try(:call, self) || send(stream) }
end

# Same as <tt>#broadcasts_to</tt>, but the designated stream is automatically set to the current model.
def broadcasts(inserts_by: :append, target: broadcast_target_default)
after_create_commit -> { broadcast_action_later action: inserts_by, target: target.try(:call, self) || target }
# Same as <tt>#broadcasts_to</tt>, 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 <tt>stream</tt>.
def broadcasts(stream = model_name.plural, inserts_by: :append, target: broadcast_target_default)
after_create_commit -> { broadcast_action_later_to stream, action: inserts_by, target: target.try(:call, self) || target }
after_update_commit -> { broadcast_replace_later }
after_destroy_commit -> { broadcast_remove }
end
Expand Down
2 changes: 1 addition & 1 deletion test/dummy/app/models/article.rb
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,7 @@ class Article < ApplicationRecord

validates :body, presence: true

broadcasts target: "overriden-target"
broadcasts "overriden-stream", target: "overriden-target"

def to_gid_param
to_param
Expand Down
2 changes: 1 addition & 1 deletion test/streams/broadcastable_test.rb
Original file line number Diff line number Diff line change
Expand Up @@ -121,7 +121,7 @@ class Turbo::BroadcastableArticleTest < ActionCable::Channel::TestCase
include ActiveJob::TestHelper, Turbo::Streams::ActionHelper

test "creating an article broadcasts to the overriden target with a string" do
assert_broadcast_on "body", turbo_stream_action_tag("append", target: "overriden-target", template: "<p>Body</p>\n") do
assert_broadcast_on "overriden-stream", turbo_stream_action_tag("append", target: "overriden-target", template: "<p>Body</p>\n") do
perform_enqueued_jobs do
Article.create!(body: "Body")
end
Expand Down