Class: JSONSelect

Inherits:
Object
  • Object
show all
Defined in:
lib/json_select.rb,
lib/json_select/version.rb,
lib/json_select/selector.rb

Defined Under Namespace

Modules: Ast, Selector Classes: SelectorParser

Constant Summary

ParseError =
Class.new(RuntimeError)
VERSION =
"0.1.2"
@@parser_cache =
{}

Instance Attribute Summary (collapse)

Class Method Summary (collapse)

Instance Method Summary (collapse)

Constructor Details

- (JSONSelect) initialize(src, use_parser_cache = true)

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
# 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
end

Instance Attribute Details

- (Object) ast (readonly)

Returns the value of attribute ast



3
4
5
# File 'lib/json_select/selector.rb', line 3

def ast
  @ast
end

Class Method Details

+ (Object) reset_cache!



7
8
9
# File 'lib/json_select/selector.rb', line 7

def self.reset_cache!
  @@parser_cache.clear
end

Instance Method Details

- (Object) match(object) Also known as: =~

Returns the first matching child in `object`



48
49
50
51
52
53
54
# File 'lib/json_select/selector.rb', line 48

def match(object)
  _each(@ast, object, nil, nil, nil, 0) do |object|
    return object
  end

  return nil
end

- (Object) matches(object)

Returns all matching children in `object`



59
60
61
62
63
64
65
66
67
# File 'lib/json_select/selector.rb', line 59

def matches(object)
  matches = []

  _each(@ast, object, nil, nil, nil, 0) do |object|
    matches << object
  end

  matches
end

- (Object) test(object) Also known as: ===

Returns true if `object` has any matching children.



70
71
72
73
74
75
76
# File 'lib/json_select/selector.rb', line 70

def test(object)
  _each(@ast, object, nil, nil, nil, 0) do |object|
    return true
  end

  return false
end