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

Fix unwanted model retention when using class methods from Turbo::Broadcastable with locals #710

Open
wants to merge 1 commit into
base: main
Choose a base branch
from
Open
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
2 changes: 1 addition & 1 deletion app/models/concerns/turbo/broadcastable.rb
Original file line number Diff line number Diff line change
Expand Up @@ -518,7 +518,7 @@ def broadcast_rendering_with_defaults(options)
options.tap do |o|
# Add the current instance into the locals with the element name (which is the un-namespaced name)
# as the key. This parallels how the ActionView::ObjectRenderer would create a local variable.
o[:locals] = (o[:locals] || {}).reverse_merge!(model_name.element.to_sym => self).compact
o[:locals] = (o[:locals] || {}).reverse_merge(model_name.element.to_sym => self).compact

if o[:html] || o[:partial]
return o
Expand Down
3 changes: 2 additions & 1 deletion test/dummy/app/models/comment.rb
Original file line number Diff line number Diff line change
Expand Up @@ -5,5 +5,6 @@ class Comment < ApplicationRecord

broadcasts_to ->(comment) { [comment.article, :comments] },
target: ->(comment) { "article_#{comment.article_id}_comments" },
partial: "comments/different_comment"
partial: "comments/different_comment",
locals: { highlight: true }
end
17 changes: 17 additions & 0 deletions test/streams/broadcastable_test.rb
Original file line number Diff line number Diff line change
Expand Up @@ -441,6 +441,23 @@ class Turbo::BroadcastableCommentTest < ActionCable::Channel::TestCase
end
end

test "creating a second comment while using locals broadcasts the second comment" do
stream = "#{@article.to_gid_param}:comments"
target = "article_#{@article.id}_comments"

assert_broadcast_on stream, turbo_stream_action_tag("append", target: target, template: %(<p class="different">comment</p>\n)) do
perform_enqueued_jobs do
@article.comments.create!(body: "comment")
end
end

assert_broadcast_on stream, turbo_stream_action_tag("append", target: target, template: %(<p class="different">another comment</p>\n)) do
perform_enqueued_jobs do
@article.comments.create!(body: "another comment")
end
end
end

test "updating a comment broadcasts" do
comment = @article.comments.create!(body: "random")
stream = "#{@article.to_gid_param}:comments"
Expand Down
Loading