Class: TurboCable::BroadcastJob

Inherits:
ApplicationJob show all
Defined in:
app/jobs/turbo_cable/broadcast_job.rb

Instance Method Summary collapse

Instance Method Details

#perform(stream_name, action:, model_gid: nil, target: nil, partial: nil, html: nil, locals: {}) ⇒ Object



5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
# File 'app/jobs/turbo_cable/broadcast_job.rb', line 5

def perform(stream_name, action:, model_gid: nil, target: nil, partial: nil, html: nil, locals: {})
  # Resolve model from GlobalID if provided
  model = GlobalID::Locator.locate(model_gid) if model_gid

  # Determine target
  target ||= "#{model.class.name.underscore}_#{model.id}" if model

  # Generate content HTML
  content_html = if html
    html
  elsif partial
    # Render partial with locals
    ApplicationController.render(partial: partial, locals: locals.merge(model ? { model.class.name.underscore.to_sym => model } : {}))
  elsif model
    # Render default partial for this model
    ApplicationController.render(partial: model, locals: locals)
  else
    raise ArgumentError, "Must provide html, partial, or model"
  end

  # Generate Turbo Stream HTML
  turbo_stream_html = if action.to_sym == :remove
    "      <turbo-stream action=\"remove\" target=\"\#{target}\">\n      </turbo-stream>\n    HTML\n  else\n    <<~HTML\n      <turbo-stream action=\"\#{action}\" target=\"\#{target}\">\n        <template>\n          \#{content_html}\n        </template>\n      </turbo-stream>\n    HTML\n  end\n\n  # Broadcast via HTTP POST\n  broadcast_turbo_stream(stream_name, turbo_stream_html)\nend\n"