Class: Thredded::SearchParser

Inherits:
Object
  • Object
show all
Defined in:
lib/thredded/search_parser.rb

Instance Method Summary collapse

Constructor Details

#initialize(query) ⇒ SearchParser

Returns a new instance of SearchParser.



3
4
5
6
# File 'lib/thredded/search_parser.rb', line 3

def initialize(query)
  @query = query
  @keywords = %w(in by order)
end

Instance Method Details

#parse ⇒ Object



8
9
10
11
12
# File 'lib/thredded/search_parser.rb', line 8

def parse
  parsed_input = parse_keywords
  parsed_input['text'] = parse_text
  parsed_input
end

#parse_keywords ⇒ Object



14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
# File 'lib/thredded/search_parser.rb', line 14

def parse_keywords
  found_terms_hash = {}

  @keywords.each do |keyword|
    regex = Regexp.new(keyword + '\s*:\s*\w+', Regexp::IGNORECASE)
    keyword_scan = @query.scan(regex)
    @query = @query.gsub(regex, '')

    if keyword_scan.present?
      keyword_scan.each do |term|
        keyword_term = term.gsub(' ', '').split(':')

        if found_terms_hash[keyword].nil?
          found_terms_hash[keyword] = []
        end

        found_terms_hash[keyword] << keyword_term[1]
      end
    end
  end

  found_terms_hash
end

#parse_text ⇒ Object



38
39
40
41
42
43
# File 'lib/thredded/search_parser.rb', line 38

def parse_text
  regex = Regexp.new('\"[^"]*\"')
  found_terms = @query.scan(regex)
  @query = @query.sub(regex, '')
  found_terms.concat(@query.split(/\s+/))
end