|
| 1 | +# frozen_string_literal: true |
| 2 | + |
| 3 | +class Detector |
| 4 | + # Detector::SuggestedResourcePattern handles detections for patterns stored in our SuggestedPattern model |
| 5 | + class SuggestedResourcePattern |
| 6 | + attr_reader :detections |
| 7 | + |
| 8 | + # shared singleton methods |
| 9 | + extend Detector::BulkChecker |
| 10 | + |
| 11 | + def initialize(phrase) |
| 12 | + @detections = {} |
| 13 | + check_patterns(phrase) |
| 14 | + end |
| 15 | + |
| 16 | + # check_patterns loops through all stored patterns from SuggestedPattern model, checks to see if they produce |
| 17 | + # matches for the incoming `phrase`, and if so creates a Hash with useful data |
| 18 | + # |
| 19 | + # @note Not using shared PatternChecker as we want to include additional data in the returned object |
| 20 | + # @param phrase [String]. A string representation of a searchterm (not an actual Term object) |
| 21 | + # @return primarily intended to add matches to @detections |
| 22 | + def check_patterns(phrase) |
| 23 | + sps = [] |
| 24 | + SuggestedPattern.find_each do |sp| |
| 25 | + next unless Regexp.new(sp.pattern).match(phrase) |
| 26 | + |
| 27 | + sps << { |
| 28 | + shortcode: sp.shortcode, |
| 29 | + title: sp.title, |
| 30 | + url: sp.url |
| 31 | + } |
| 32 | + @detections = sps |
| 33 | + end |
| 34 | + end |
| 35 | + |
| 36 | + # The record method will consult the set of regex-based detectors that are defined in |
| 37 | + # SuggestedPattern records. Any matches will be registered as Detection records. |
| 38 | + # |
| 39 | + # @note There are multiple patterns within SuggestedPattern records. Each check is capable of generating |
| 40 | + # a separate Detection record. |
| 41 | + # |
| 42 | + # @return nil |
| 43 | + def self.record(term) |
| 44 | + sp = Detector::SuggestedResourcePattern.new(term.phrase) |
| 45 | + |
| 46 | + sp.detections.each do |
| 47 | + Detection.find_or_create_by( |
| 48 | + term:, |
| 49 | + detector: Detector.where(name: 'SuggestedResourcePattern').first, |
| 50 | + detector_version: ENV.fetch('DETECTOR_VERSION', 'unset') |
| 51 | + ) |
| 52 | + end |
| 53 | + |
| 54 | + nil |
| 55 | + end |
| 56 | + end |
| 57 | +end |
0 commit comments