Skip to content

Commit

Permalink
Turbo::Broadcastable#broadcasts broadcasts creates to model_name.plur…
Browse files Browse the repository at this point in the history
…al stream (#295)
  • Loading branch information
Exterm1nate authored May 22, 2022
1 parent edfdae9 commit 0854666
Show file tree
Hide file tree
Showing 3 changed files with 6 additions and 5 deletions.
7 changes: 4 additions & 3 deletions app/models/concerns/turbo/broadcastable.rb
Original file line number Diff line number Diff line change
Expand Up @@ -72,9 +72,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 @@ -134,7 +134,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

0 comments on commit 0854666

Please sign in to comment.