Method: JSONSelect#initialize

Defined in:
lib/json_select/selector.rb

#initialize(src, use_parser_cache = true) ⇒ JSONSelect

Returns a new instance of JSONSelect.



11
12
13
14
15
16
17
18
19
20
21
22
23
24
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
56
57
58
# File 'lib/json_select/selector.rb', line 11

def initialize(src, use_parser_cache=true)
  case src

  when String
    ast = nil

    if use_parser_cache
      ast = @@parser_cache[src]
    end

    if ast
      @ast = ast

    else
      parser = JSONSelect::SelectorParser.new
      tree   = parser.parse(src)
      unless tree
        raise JSONSelect::ParseError, parser.failure_reason
      end

      @ast = tree.to_ast

      if use_parser_cache
        @@parser_cache[src] = ast
      end
    end

  when Array
    @ast = src

  else
    raise ArgumentError, "Expected a string for ast"

  end

  @helpers = Module.new
  @helpers.send(:extend,
    JSONSelect::KeyHelpers,
    JSONSelect::TypeHelpers,
    JSONSelect::SizeHelpers,
    JSONSelect::DepthHelpers,
    JSONSelect::PositionHelpers)

  @helper_methods = {}
  (@helpers.public_methods - Module.public_methods).map do |name|
    @helper_methods[name.to_sym] = @helpers.method(name)
  end
end