Class: Whoops::MongoidSearchParser

Inherits:
Object
  • Object
show all
Defined in:
app/models/whoops/mongoid_search_parser.rb

Overview

Parses text to create corresponding mongoid conditions. See README for details on syntax.

Instance Attribute Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(query) ⇒ MongoidSearchParser

Returns a new instance of MongoidSearchParser.



5
6
7
# File 'app/models/whoops/mongoid_search_parser.rb', line 5

def initialize(query)
  self.query = query
end

Instance Attribute Details

#queryObject

Returns the value of attribute query.



4
5
6
# File 'app/models/whoops/mongoid_search_parser.rb', line 4

def query
  @query
end

Instance Method Details

#conditionsObject



9
10
11
12
13
14
15
16
17
18
19
20
# File 'app/models/whoops/mongoid_search_parser.rb', line 9

def conditions
  self.query.split("\n").inject({}) do |conditions, line|
    line.strip!
    next(conditions) if line.empty?
    
    parsed = parse_line(line)
    key = parsed[:method] ? parsed[:key].send(parsed[:method]) : parsed[:key]
    
    conditions[key] = parsed[:value]
    conditions
  end
end

#parse_line(line) ⇒ Object



22
23
24
25
26
27
28
29
30
31
32
33
# File 'app/models/whoops/mongoid_search_parser.rb', line 22

def parse_line(line)
  key, method, value = line.match(/([^\s]*?)(#[^\s]*)? ([^#]*)/)[1..3]
  
  key = key.sub(/:$/, '').to_sym
  method = method.gsub(/(^#|:$)/, '').to_sym if method
  value = parse_value(value)
  {
    :key => key,
    :method => method,
    :value => value
  }
end

#parse_value(value) ⇒ Object

Allows user to enter hashes or array



36
37
38
39
40
41
# File 'app/models/whoops/mongoid_search_parser.rb', line 36

def parse_value(value)
  value = value.strip
  # value = "!ruby/regexp \"#{value}\"" if value =~ /^\/.*\/$/
  value.gsub!(/!r(\/.*?\/)/, %Q{!ruby/regexp "\\1"})
  return YAML.load(value)
end