Class: SearchAndReplace

Inherits:
Object
  • Object
show all
Defined in:
lib/search_and_replace.rb

Instance Method Summary collapse

Constructor Details

#initializeSearchAndReplace

Returns a new instance of SearchAndReplace.



7
8
9
10
# File 'lib/search_and_replace.rb', line 7

def initialize
  @dl = KeywordProspector.new
  @tree_initialized = false
end

Instance Method Details

#add_replacement(original, replacement) ⇒ Object



12
13
14
# File 'lib/search_and_replace.rb', line 12

def add_replacement(original, replacement)
  @dl.add(original, replacement)
end

#initialize_treeObject



16
17
18
19
20
21
# File 'lib/search_and_replace.rb', line 16

def initialize_tree
  unless @tree_initialized
    @dl.construct_fail
    @tree_initialized = true
  end
end

#replace_text(text) ⇒ Object



23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
# File 'lib/search_and_replace.rb', line 23

def replace_text(text)
  unless @tree_initialized
    initialize_tree
  end

  matches = @dl.process(text.downcase, :filter_overlaps => true)

  retval = ""
  current_index = 0
  matches.each do |match|
    if (current_index < match.start_idx)
      retval += text[current_index, match.start_idx - current_index]
    end

    retval += match.output
    current_index = match.end_idx
  end

  retval += text[current_index, text.length] unless current_index == text.length

  retval
end