Class: TrieMatcher::PatternMatcher
- Inherits:
-
Object
- Object
- TrieMatcher::PatternMatcher
- 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
-
#add_pattern(prefix, pattern) {|match| ... } ⇒ Object
Register a pattern, along with a static prefix.
-
#initialize ⇒ PatternMatcher
constructor
Build an empty pattern matcher.
-
#match(string) ⇒ Object
Match a string against all registered patterns efficiently.
Constructor Details
#initialize ⇒ PatternMatcher
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
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
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 |