Module: JsonQuery::Data

Defined in:
lib/json_query/data.rb

Class Method Summary collapse

Class Method Details

.build_paths(path: nil, data:, paths: []) ⇒ Object



40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
# File 'lib/json_query/data.rb', line 40

def self.build_paths(path: nil, data:, paths: [])
  if is_set?(data)
    data.map do |key, value|
      new_key = [path, key].compact.join(".")
      paths << new_key
      build_paths(path: new_key, data: value, paths: paths)
    end
  elsif is_list?(data)
    data.map.with_index do |value, index|
      new_key = [path, "[#{index}]"].compact.join
      paths << new_key
      build_paths(path: new_key, data: value, paths: paths)
    end
  else
    # it is a scalar, ignoring
  end
  paths
end

.is_list?(value) ⇒ Boolean



32
33
34
# File 'lib/json_query/data.rb', line 32

def self.is_list?(value)
  value.is_a?(Array)
end

.is_set?(value) ⇒ Boolean



36
37
38
# File 'lib/json_query/data.rb', line 36

def self.is_set?(value)
  value.is_a?(Hash)
end

.walk(data:, path:) ⇒ Object



4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
# File 'lib/json_query/data.rb', line 4

def self.walk(data:, path:)
  current = data
  path.each do |segment|
    results = segment.match(/^(.*)\[([0-9]+)\]$/)
    key, index = if results
      results.captures
    else
      [segment, nil]
    end
    if current.has_key?(key)
      current = current[key]
    else
      puts "Path #{path.join(".")} is not valid: the key `#{segment}` is not present."
      exit 1
    end
    if index
      index = index.to_i
      if is_list?(current) && current.count > index
        current = current[index]
      else
        puts "Path #{path.join(".")} is not valid: not a list of the index is out of bound."
        exit 1
      end
    end
  end
  current
end