summaryrefslogtreecommitdiff
path: root/lib/chef_zero/solr/query/regexpable_query.rb
blob: 62d7fc73336c66ac47a3ac2e45c81dd559e304c3 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
module ChefZero
  module Solr
    module Query
      class RegexpableQuery
        def initialize(regexp_string, literal_string)
          @regexp_string = regexp_string
          # Surround the regexp with word boundaries
          @regexp = Regexp.new("(^|#{NON_WORD_CHARACTER})#{regexp_string}($|#{NON_WORD_CHARACTER})", true)
          @literal_string = literal_string
        end

        attr_reader :literal_string
        attr_reader :regexp_string
        attr_reader :regexp

        def matches_doc?(doc)
          matches_values?(doc[DEFAULT_FIELD])
        end

        def matches_values?(values)
          values.any? { |value| !@regexp.match(value).nil? }
        end

        DEFAULT_FIELD = "text"
        WORD_CHARACTER = "[A-Za-z0-9@._':\-]"
        NON_WORD_CHARACTER = "[^A-Za-z0-9@._':\-]"
      end
    end
  end
end