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>