Skip to content

Instantly share code, notes, and snippets.

@stevepolitodesign
Last active May 30, 2021 16:10
Show Gist options
  • Save stevepolitodesign/5b2767eb51abf436d50ad2bf06d1edf9 to your computer and use it in GitHub Desktop.
Save stevepolitodesign/5b2767eb51abf436d50ad2bf06d1edf9 to your computer and use it in GitHub Desktop.
Turbo broadcast_action_to Example
class Screenshot < ApplicationRecord
  belongs_to :webpage

  after_create_commit :broadcast_later

  private

    def broadcast_later
      # We could use `broadcast_action_to` but using `broadcast_action_later_to`
      # will make this run asynchronously.

      self.broadcast_action_later_to(
        # The stream. Note the we're scoping it to the user.
        [self.webpage.website.user, :screenshots],
        
        # How we'll update the DOM. In this case we'll replace the element.
        action: :replace,
        
        # The target element the action will take place on.
        target: "screenshots",
        
        # The partial to use along with the options to pass the partial.  
        partial: "screenshots/screenshot",
        layout: "screenshots/layouts/column",
      )
    end
end
# This is the stream we're refering to above
<%= turbo_stream_from(@webpage.website.user, :screenshots) %>

# This is the target element that we're refering with the target argument.
# Its content will be replaced by the partial.
<div id="screenshots">
    <span class="visually-hidden">Generating screenshot...</span>
</div>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment