class OpenUI::Rails::Stream::Transports::TurboStreams

Broadcasts each envelope as a Turbo Stream that appends an ‘openui-envelope` element to a target already in the DOM.

The small ‘openui-envelope` Stimulus controller turns that element into an `openui:envelope` event and removes itself, so no inline script is used and no Content Security Policy relaxation is needed.

turbo-rails is looked up lazily and may be injected via ‘turbo:`; the Gem never hard-depends on it.

Constants

ELEMENT_TAG

Attributes

stream[R]
target[R]

Public Class Methods

new(stream, target:, turbo: nil) click to toggle source
# File lib/openui/rails/stream/transports/turbo_streams.rb, line 24
def initialize(stream, target:, turbo: nil)
  raise ConfigurationError, "a stream is required" if stream.nil?
  if target.nil? || target.to_s.empty?
    raise ConfigurationError, "a target is required"
  end

  @stream = stream
  @target = target.to_s
  @turbo = turbo
end

Public Instance Methods

broadcast(envelope) click to toggle source
# File lib/openui/rails/stream/transports/turbo_streams.rb, line 35
def broadcast(envelope)
  channel.broadcast_append_to(stream, target: target, content: element(envelope))
end
element(envelope) click to toggle source

The HTML fragment a Turbo Stream appends. Kept public so tests can assert on escaping without a Turbo dependency.

# File lib/openui/rails/stream/transports/turbo_streams.rb, line 41
def element(envelope)
  payload = ERB::Util.html_escape(JSON.generate(envelope.to_h))
  %(<#{ELEMENT_TAG} data-controller="openui-envelope" data-openui-envelope-payload="#{payload}"></#{ELEMENT_TAG}>)
end