Skip to content

Commit

Permalink
Support target: as Array argument (#448)
Browse files Browse the repository at this point in the history
  • Loading branch information
seanpdoyle authored Apr 17, 2023
1 parent 728b963 commit 0661376
Show file tree
Hide file tree
Showing 2 changed files with 30 additions and 2 deletions.
16 changes: 14 additions & 2 deletions app/helpers/turbo/streams/action_helper.rb
Original file line number Diff line number Diff line change
Expand Up @@ -11,6 +11,18 @@ module Turbo::Streams::ActionHelper
#
# turbo_stream_action_tag "replace", targets: "message_1", template: %(<div id="message_1">Hello!</div>)
# # => <turbo-stream action="replace" targets="message_1"><template><div id="message_1">Hello!</div></template></turbo-stream>
#
# The `target:` keyword option will forward `ActionView::RecordIdentifier#dom_id`-compatible arguments to
# `ActionView::RecordIdentifier#dom_id`
#
# message = Message.find(1)
# turbo_stream_action_tag "remove", target: message
# # => <turbo-stream action="remove" target="message_1"></turbo-stream>
#
# message = Message.find(1)
# turbo_stream_action_tag "remove", target: [message, :special]
# # => <turbo-stream action="remove" target="special_message_1"></turbo-stream>
#
def turbo_stream_action_tag(action, target: nil, targets: nil, template: nil, **attributes)
template = action.to_sym == :remove ? "" : tag.template(template.to_s.html_safe)

Expand All @@ -25,8 +37,8 @@ def turbo_stream_action_tag(action, target: nil, targets: nil, template: nil, **

private
def convert_to_turbo_stream_dom_id(target, include_selector: false)
if target.respond_to?(:to_key)
"#{"#" if include_selector}#{ActionView::RecordIdentifier.dom_id(target)}"
if Array(target).any? { |value| value.respond_to?(:to_key) }
"#{"#" if include_selector}#{ActionView::RecordIdentifier.dom_id(*target)}"
else
target
end
Expand Down
16 changes: 16 additions & 0 deletions test/streams/action_helper_test.rb
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,22 @@
class Turbo::ActionHelperTest < ActionCable::Channel::TestCase
include Turbo::Streams::ActionHelper

test "target responds to #to_key" do
message = Message.new(id: 1)

stream = "<turbo-stream action=\"append\" target=\"message_1\"><template></template></turbo-stream>"

assert_equal stream, turbo_stream_action_tag("append", target: message)
end

test "target passed as array of dom_id arguments" do
message = Message.new(id: 1)

stream = "<turbo-stream action=\"append\" target=\"special_message_1\"><template></template></turbo-stream>"

assert_equal stream, turbo_stream_action_tag("append", target: [message, :special])
end

test "no template" do
stream = "<turbo-stream action=\"append\" target=\"message_1\"><template></template></turbo-stream>"

Expand Down

0 comments on commit 0661376

Please sign in to comment.