From 0661376c32f81ee39c01c903273746180b7db391 Mon Sep 17 00:00:00 2001 From: Sean Doyle Date: Mon, 17 Apr 2023 18:39:50 -0400 Subject: [PATCH] Support `target:` as Array argument (#448) --- app/helpers/turbo/streams/action_helper.rb | 16 ++++++++++++++-- test/streams/action_helper_test.rb | 16 ++++++++++++++++ 2 files changed, 30 insertions(+), 2 deletions(-) diff --git a/app/helpers/turbo/streams/action_helper.rb b/app/helpers/turbo/streams/action_helper.rb index e0392661..37e6e545 100644 --- a/app/helpers/turbo/streams/action_helper.rb +++ b/app/helpers/turbo/streams/action_helper.rb @@ -11,6 +11,18 @@ module Turbo::Streams::ActionHelper # # turbo_stream_action_tag "replace", targets: "message_1", template: %(
Hello!
) # # => + # + # 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 + # # => + # + # message = Message.find(1) + # turbo_stream_action_tag "remove", target: [message, :special] + # # => + # 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) @@ -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 diff --git a/test/streams/action_helper_test.rb b/test/streams/action_helper_test.rb index 59e503a3..d1818cd0 100644 --- a/test/streams/action_helper_test.rb +++ b/test/streams/action_helper_test.rb @@ -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 = "" + + 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 = "" + + assert_equal stream, turbo_stream_action_tag("append", target: [message, :special]) + end + test "no template" do stream = ""