Class: TrieMatcher::PatternMatcher

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

Overview

Convenience class for matching specific patterns, accelerated by a static prefix.

This is extremely useful for matching complex patterns such as user agents or url routes

Instance Method Summary collapse

Constructor Details

#initializePatternMatcher

Build an empty pattern matcher



8
9
10
# File 'lib/trie_matcher/pattern_matcher.rb', line 8

def initialize
  @trie = TrieMatcher.new
end

Instance Method Details

#add_pattern(prefix, pattern) {|match| ... } ⇒ Object

Register a pattern, along with a static prefix

Parameters:

  • prefix (String)

    a static prefix that indicates this pattern should be tested

  • pattern (Regexp)

    a pattern to test against

Yields:

  • (match)

    executed if a positive match is made

Yield Parameters:

  • match (MatchData)

    the match data from the pattern



18
19
20
21
# File 'lib/trie_matcher/pattern_matcher.rb', line 18

def add_pattern(prefix, pattern, &block)
  @trie[prefix] ||= {}
  @trie[prefix][pattern] = block
end

#match(string) ⇒ Object

Match a string against all registered patterns efficiently.

Calls the block registered against any matching pattern, and passes in the match data

Parameters:

  • string (String)

    the string to match against



28
29
30
31
32
33
34
35
# File 'lib/trie_matcher/pattern_matcher.rb', line 28

def match(string)
  result = @trie[string]
  return nil unless result
  result.each do |pattern, block|
    match = pattern.match(string)
    block.call(match) if match
  end
end