Skip to content

Add the ability to customize the key used for the instance in the bro… #741

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

Open
wants to merge 2 commits into
base: main
Choose a base branch
from
Open
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
12 changes: 11 additions & 1 deletion app/models/concerns/turbo/broadcastable.rb
Original file line number Diff line number Diff line change
Expand Up @@ -218,6 +218,12 @@ def broadcasts_refreshes(stream = model_name.plural)
after_destroy_commit -> { broadcast_refresh }
end

# All instances will use the return of this method for the key in the locals. Overwrite if you want something else than <tt>model_name.element.to_sym</tt>.
# This default parallels how the ActionView::ObjectRenderer would create a local variable.
def broadcast_locals_instance_key_default
model_name.element.to_sym
end

# All default targets will use the return of this method. Overwrite if you want something else than <tt>model_name.plural</tt>.
def broadcast_target_default
model_name.plural
Expand Down Expand Up @@ -504,6 +510,10 @@ def broadcast_render_later_to(*streamables, **rendering)
end

private
def broadcast_locals_instance_key_default
self.class.broadcast_locals_instance_key_default
end

def broadcast_target_default
self.class.broadcast_target_default
end
Expand All @@ -518,7 +528,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(broadcast_locals_instance_key_default => self).compact

if o[:html] || o[:partial]
return o
Expand Down