Class: JsonPath::Parser

Inherits:
Object
  • Object
show all
Defined in:
lib/jsonpath/parser.rb

Overview

Parser parses and evaluates an expression passed to @_current_node.

Instance Method Summary collapse

Constructor Details

#initialize(node) ⇒ Parser

Returns a new instance of Parser.



7
8
9
# File 'lib/jsonpath/parser.rb', line 7

def initialize(node)
  @_current_node = node
end

Instance Method Details

#parse(exp) ⇒ Object



11
12
13
14
15
16
17
18
19
20
21
22
23
# File 'lib/jsonpath/parser.rb', line 11

def parse(exp)
  exps = exp.split(/(&&)|(\|\|)/)
  ret = parse_exp(exps.shift)
  exps.each_with_index do |item, index|
    case item
    when '&&'
      ret &&= parse_exp(exps[index + 1])
    when '||'
      ret ||= parse_exp(exps[index + 1])
    end
  end
  ret
end

#parse_exp(exp) ⇒ Object



25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
# File 'lib/jsonpath/parser.rb', line 25

def parse_exp(exp)
  exp = exp.sub(/@/, '').gsub(/^\(/, '').gsub(/\)$/, '').gsub(/"/, '\'').strip
  scanner = StringScanner.new(exp)
  elements = []
  until scanner.eos?
    if scanner.scan(/\./)
      sym = scanner.scan(/\w+/)
      op = scanner.scan(/./)
      num = scanner.scan(/\d+/)
      return @_current_node.send(sym.to_sym).send(op.to_sym, num.to_i)
    end
    if t = scanner.scan(/\['[a-zA-Z@&\*\/\$%\^\?_]+'\]+/)
      elements << t.gsub(/\[|\]|'|\s+/, '')
    elsif t = scanner.scan(/(\s+)?[<>=][=~]?(\s+)?/)
      operator = t
    elsif t = scanner.scan(/(\s+)?'?.*'?(\s+)?/)
      operand = operator.strip == "=~" ? t.to_regexp : t.delete("'").strip
    elsif t = scanner.scan(/\/\w+\//)

    elsif t = scanner.scan(/.*/)
      raise "Could not process symbol: #{t}"
    end
  end
  el = dig(elements, @_current_node)
  return false unless el
  return true if operator.nil? && el

  el = Float(el) rescue el
  operand = Float(operand) rescue operand
  el.send(operator.strip, operand)
end