class Rewriter
Provides text rewriting functionality with match-based substitutions.
Definitions
def initialize(text)
Initialize a new rewriter.
Signature
-
parameter
text
String
The text to rewrite.
Implementation
def initialize(text)
@text = text
@matches = []
end
def <<(match)
Add a match to the rewriter.
Signature
-
parameter
match
Match
The match to add.
Implementation
def << match
@matches << match
end
def text_for(range)
Returns a chunk of raw text with no formatting.
Implementation
def text_for(range)
@text[range]
end
def apply(output = [])
Apply all matches to generate the rewritten output.
Signature
-
parameter
output
Array
The output array to append to.
Implementation
def apply(output = [])
offset = 0
@matches.sort.each do |match|
if match.offset > offset
output << text_for(offset...match.offset)
offset = match.offset
elsif match.offset < offset
# Match intersects last output buffer.
next
end
offset += match.apply(output, self)
end
if offset < @text.size
output << text_for(offset...@text.size)
end
return output
end
def link_to(definition, text)
Generate a link to a definition.
Signature
-
parameter
definition
Definition
The definition to link to.
-
parameter
text
String
The text to display for the link.
Implementation
def link_to(definition, text)
"[#{text}]"
end