Class: JsonPath

Inherits:
Object
  • Object
show all
Defined in:
lib/jsonpath.rb,
lib/jsonpath/proxy.rb,
lib/jsonpath/version.rb,
lib/jsonpath/enumerable.rb

Defined Under Namespace

Classes: Enumerable, Proxy

Constant Summary collapse

VERSION =
'0.4.0'

Instance Attribute Summary collapse

Class Method Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(path, opts = nil) ⇒ JsonPath

Returns a new instance of JsonPath.



10
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
# File 'lib/jsonpath.rb', line 10

def initialize(path, opts = nil)
  @opts = opts
  scanner = StringScanner.new(path)
  @path = []
  bracket_count = 0
  while not scanner.eos?
    if token = scanner.scan(/\$/)
      @path << token
    elsif token = scanner.scan(/@/)
      @path << token
    elsif token = scanner.scan(/[a-zA-Z_]+/)
      @path << "['#{token}']"
    elsif token = scanner.scan(/'(.*?)'/)
      @path << "[#{token}]"
    elsif token = scanner.scan(/\[/)
      count = 1
      while !count.zero?
        if t = scanner.scan(/\[/)
          token << t
          count += 1
        elsif t = scanner.scan(/\]/)
          token << t
          count -= 1
        elsif t = scanner.scan(/[^\[\]]*/)
          token << t
        end
      end
      @path << token
    elsif token = scanner.scan(/\.\./)
      @path << token
    elsif scanner.scan(/\./)
    elsif token = scanner.scan(/\*/)
      @path << token
    elsif token = scanner.scan(/./)
      @path.last << token
    end
  end
end

Instance Attribute Details

#pathObject (readonly)

Returns the value of attribute path.



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

def path
  @path
end

Class Method Details

.for(obj) ⇒ Object



65
66
67
# File 'lib/jsonpath.rb', line 65

def self.for(obj)
  Proxy.new(obj)
end

.on(object, path, opts = nil) ⇒ Object



61
62
63
# File 'lib/jsonpath.rb', line 61

def self.on(object, path, opts = nil)
  self.new(path, opts).on(object)
end

Instance Method Details

#enum_on(object) ⇒ Object



57
58
59
# File 'lib/jsonpath.rb', line 57

def enum_on(object)
  JsonPath::Enumerable.new(self, object, @opts)
end

#first(object) ⇒ Object



53
54
55
# File 'lib/jsonpath.rb', line 53

def first(object)
  enum_on(object).first
end

#on(object) ⇒ Object



49
50
51
# File 'lib/jsonpath.rb', line 49

def on(object)
  enum_on(object).to_a
end