diff --git a/app/models/turbo/streams/tag_builder.rb b/app/models/turbo/streams/tag_builder.rb index 3e818e46..99a2aa47 100644 --- a/app/models/turbo/streams/tag_builder.rb +++ b/app/models/turbo/streams/tag_builder.rb @@ -22,6 +22,24 @@ # <%= turbo_stream.append dom_id(topic_merge) do %> # <%= link_to topic_merge.topic.name, topic_path(topic_merge.topic) %> # <% end %> +# +# To integrate with custom actions, extend this class in response to the :turbo_streams_tag_builder load hook: +# +# ActiveSupport.on_load :turbo_streams_tag_builder do +# def highlight(target) +# action :highlight, target +# end +# +# def highlight_all(targets) +# action_all :highlight, targets +# end +# end +# +# turbo_stream.highlight "my-element" +# # => +# +# turbo_stream.highlight_all ".my-selector" +# # => class Turbo::Streams::TagBuilder include Turbo::Streams::ActionHelper @@ -246,4 +264,6 @@ def render_record(possible_record) @view_context.render(partial: record, formats: :html) end end + + ActiveSupport.run_load_hooks :turbo_streams_tag_builder, self end diff --git a/test/dummy/config/initializers/turbo.rb b/test/dummy/config/initializers/turbo.rb new file mode 100644 index 00000000..24fec68d --- /dev/null +++ b/test/dummy/config/initializers/turbo.rb @@ -0,0 +1,9 @@ +ActiveSupport.on_load :turbo_streams_tag_builder do + def highlight(target) + action :highlight, target + end + + def highlight_all(targets) + action_all :highlight, targets + end +end diff --git a/test/streams/streams_helper_test.rb b/test/streams/streams_helper_test.rb index 6ce36438..e8511dfb 100644 --- a/test/streams/streams_helper_test.rb +++ b/test/streams/streams_helper_test.rb @@ -3,6 +3,8 @@ class TestChannel < ApplicationCable::Channel; end class Turbo::StreamsHelperTest < ActionView::TestCase + attr_accessor :formats + test "with streamable" do assert_dom_equal \ %(), @@ -33,4 +35,12 @@ class Turbo::StreamsHelperTest < ActionView::TestCase turbo_stream_from("messages", channel: "NonExistentChannel", data: {payload: 1}) end + test "custom turbo_stream builder actions" do + assert_dom_equal <<~HTML.strip, turbo_stream.highlight("an-id") + + HTML + assert_dom_equal <<~HTML.strip, turbo_stream.highlight_all(".a-selector") + + HTML + end end