Class: Dommy::Internal::RangeTextSerializer

Inherits:
Object
  • Object
show all
Defined in:
lib/dommy/internal/range_text_serializer.rb

Overview

Collaborator that serializes a Range to its text content (Range#to_s). Walks the range's common-ancestor subtree, trimming the start/end text nodes by the boundary offsets and concatenating contributions from every intersecting text node.

Reads Range through its public surface (start_container, end_container, start_offset, end_offset, common_ancestor_container, intersects_node) — no peeking at ivars, so Range is free to refactor its internals.

Instance Method Summary collapse

Constructor Details

#initialize(range) ⇒ RangeTextSerializer

Returns a new instance of RangeTextSerializer.



15
16
17
# File 'lib/dommy/internal/range_text_serializer.rb', line 15

def initialize(range)
  @range = range
end

Instance Method Details

#serializeObject



19
20
21
22
23
24
25
26
27
28
29
30
31
32
# File 'lib/dommy/internal/range_text_serializer.rb', line 19

def serialize
  return "" unless @range.common_ancestor_container

  sc, ec = @range.start_container, @range.end_container
  so, eo = @range.start_offset, @range.end_offset

  if sc.equal?(ec) && text_node?(sc)
    return sc.data.to_s[so, eo - so].to_s
  end

  pieces = []
  walk(@range.common_ancestor_container, pieces)
  pieces.join
end