Class: LookupChain

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

Overview

Manages a list of lookup objects, prioritizing the matches from the later objects over matches from previous objects in cases of exact collisions or cases where two matches have the same length. Otherwise, when there are overlaps, the longest match always wins.

Instance Attribute Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(*lookups) ⇒ LookupChain

Returns a new instance of LookupChain.



13
14
15
16
17
18
19
20
21
# File 'lib/lookup_chain.rb', line 13

def initialize(*lookups)
  @lookups = []
  lookups.flatten!

  lookups.each do |lookup|
    check_lookup(lookup)
    @lookups << lookup
  end
end

Instance Attribute Details

#lookupsObject (readonly)

Returns the value of attribute lookups.



11
12
13
# File 'lib/lookup_chain.rb', line 11

def lookups
  @lookups
end

Instance Method Details

#<<(lookup) ⇒ Object



23
24
25
26
27
# File 'lib/lookup_chain.rb', line 23

def <<(lookup)
  check_lookup(lookup)

  self.lookups << lookup
end

#process(text) ⇒ Object



29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
# File 'lib/lookup_chain.rb', line 29

def process(text)
  matches = []

  @lookups.each do |lookup|
    new_matches = lookup.process(text)
    matches += new_matches
    matches.sort!
    i = 0
    while(i+1 < matches.size)
      (match1, match2) = matches[i,2]

      if(match1.overlap?(match2))
        if (match1.length > match2.length)
          matches.delete_at(i+1)
        elsif (match1.length < match2.length)
          matches.delete_at(i)
        else
          if (new_matches.include?(match1))
            matches.delete_at(i)
          else
            matches.delete_at(i+1)
          end
        end
      else
        i += 1
      end
    end
  end

  return matches
end