Module: Fatty::Search
Instance Method Summary collapse
- #compile_regexp(pattern, regex: false) ⇒ Object
- #compile_term_regexps(pattern) ⇒ Object
-
#match_all_terms?(haystack, query) ⇒ Boolean
Return the haystack items that match all the space-separated terms in query, regarless of order or case.
-
#split_terms(query) ⇒ Object
Split query into white-space-separated terms.
Instance Method Details
#compile_regexp(pattern, regex: false) ⇒ Object
22 23 24 25 26 27 28 29 30 31 32 33 34 35 |
# File 'lib/fatty/search.rb', line 22 def compile_regexp(pattern, regex: false) return Regexp.new(pattern) if regex terms = split_terms(pattern) flags = pattern.match?(/[[:upper:]]/) ? 0 : Regexp::IGNORECASE return Regexp.new("", flags) if terms.empty? lookaheads = terms.map { |term| "(?=.*#{Regexp.escape(term)})" }.join Regexp.new("#{lookaheads}.*", flags) end |
#compile_term_regexps(pattern) ⇒ Object
37 38 39 40 41 |
# File 'lib/fatty/search.rb', line 37 def compile_term_regexps(pattern) terms = split_terms(pattern) flags = pattern.match?(/[A-Z]/) ? 0 : Regexp::IGNORECASE terms.map { |term| Regexp.new(Regexp.escape(term), flags) } end |
#match_all_terms?(haystack, query) ⇒ Boolean
Return the haystack items that match all the space-separated terms in query, regarless of order or case.
14 15 16 17 18 19 20 |
# File 'lib/fatty/search.rb', line 14 def match_all_terms?(haystack, query) terms = split_terms(query) return true if terms.empty? text = haystack.to_s.downcase terms.all? { |term| text.include?(term.downcase) } end |
#split_terms(query) ⇒ Object
Split query into white-space-separated terms.
8 9 10 |
# File 'lib/fatty/search.rb', line 8 def split_terms(query) query.to_s.strip.split(/\s+/).reject(&:empty?) end |