module Turbo::Streams::ActionHelper
# Creates a `turbo-stream` tag according to the passed parameters. Examples:
#
# turbo_stream_action_tag "remove", target: "message_1"
# # =>
#
# turbo_stream_action_tag "replace", target: "message_1", template: %(
Hello!
)
# # => Hello!
#
# turbo_stream_action_tag "replace", targets: "message_1", template: %(Hello!
)
# # => Hello!
def turbo_stream_action_tag(action, target: nil, targets: nil, template: nil)
template = action.to_sym == :remove ? "" : "#{template}"
if target
target = convert_to_turbo_stream_dom_id(target)
%(#{template}).html_safe
elsif targets
%(#{template}).html_safe
else
raise ArgumentError, "target or targets must be supplied"
end
end
private
def convert_to_turbo_stream_dom_id(target)
target.respond_to?(:to_key) ? ActionView::RecordIdentifier.dom_id(target) : target
end
end