Class: Decode::Syntax::Rewriter

Inherits:
Object
  • Object
show all
Defined in:
lib/decode/syntax/rewriter.rb

Overview

Provides text rewriting functionality with match-based substitutions.

Instance Attribute Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(text) ⇒ Rewriter

Initialize a new rewriter.



12
13
14
15
# File 'lib/decode/syntax/rewriter.rb', line 12

def initialize(text)
  @text = text
  @matches = []
end

Instance Attribute Details

#matchesObject (readonly)

Returns the value of attribute matches.



21
22
23
# File 'lib/decode/syntax/rewriter.rb', line 21

def matches
  @matches
end

#textObject (readonly)

Returns the value of attribute text.



18
19
20
# File 'lib/decode/syntax/rewriter.rb', line 18

def text
  @text
end

#The matches to apply.(matchestoapply.) ⇒ Object (readonly)



21
# File 'lib/decode/syntax/rewriter.rb', line 21

attr :matches

#The text to rewrite.(texttorewrite.) ⇒ Object (readonly)



18
# File 'lib/decode/syntax/rewriter.rb', line 18

attr :text

Instance Method Details

#<<(match) ⇒ Object

Add a match to the rewriter.



25
26
27
28
# File 'lib/decode/syntax/rewriter.rb', line 25

def << match
  @matches << match
  return self
end

#apply(output = []) ⇒ Object

Apply all matches to generate the rewritten output.



37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
# File 'lib/decode/syntax/rewriter.rb', line 37

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

Generate a link to a definition.



63
64
65
# File 'lib/decode/syntax/rewriter.rb', line 63

def link_to(definition, text)
  "[#{text}]"
end

#text_for(range) ⇒ Object

Returns a chunk of raw text with no formatting.



31
32
33
# File 'lib/decode/syntax/rewriter.rb', line 31

def text_for(range)
  @text[range] || ""
end