Class: LiveCable::Testing::RenderState

Inherits:
Object
  • Object
show all
Defined in:
lib/live_cable/testing/render_state.rb

Overview

Reconstructs a component's rendered HTML from _refresh broadcasts, mirroring what the JavaScript client does: the first refresh carries all parts, subsequent refreshes carry only the changed parts (nil means unchanged), and child components arrive as separate results referenced by placeholders.

Constant Summary collapse

CHILD_PLACEHOLDER =
%r{<LiveCable child-live-id="(?<live_id>[^"]+)"></LiveCable>}

Instance Method Summary collapse

Constructor Details

#initializeRenderState

Returns a new instance of RenderState.



13
14
15
16
17
# File 'lib/live_cable/testing/render_state.rb', line 13

def initialize
  @parts_by_template = {}
  @last_template = nil
  @children = Hash.new { |hash, key| hash[key] = RenderState.new }
end

Instance Method Details

#apply(refresh) ⇒ Object

Parameters:

  • refresh (Hash)

    A _refresh payload ({ h:, p:, c: })



20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
# File 'lib/live_cable/testing/render_state.rb', line 20

def apply(refresh)
  refresh = refresh.as_json # Normalize symbol/string keys

  template = refresh['h'] || @last_template || 'default'
  @last_template = template

  parts = refresh['p'] || []

  if @parts_by_template.key?(template)
    parts.each_with_index do |part, index|
      @parts_by_template[template][index] = part unless part.nil?
    end
  else
    @parts_by_template[template] = parts.dup
  end

  (refresh['c'] || {}).each do |live_id, child_refresh|
    @children[live_id].apply(child_refresh)
  end
end

#htmlString

Returns The reconstructed HTML with child placeholders resolved.

Returns:

  • (String)

    The reconstructed HTML with child placeholders resolved



42
43
44
45
46
47
48
49
# File 'lib/live_cable/testing/render_state.rb', line 42

def html
  parts = @parts_by_template[@last_template]
  return '' unless parts

  parts.join.gsub(CHILD_PLACEHOLDER) do
    @children[Regexp.last_match[:live_id]].html
  end
end