Module: NanDoc::PathTardo

Included in:
Commands::Diff, SiteDiff
Defined in:
lib/nandoc/support/path-tardo.rb

Defined Under Namespace

Modules: Tardo

Class Method Summary collapse

Instance Method Summary collapse

Class Method Details

.tardo_array_index(str) ⇒ Object

This is like a really basic xpath for data structures that are composed of arrays and hashes



7
8
9
# File 'lib/nandoc/support/path-tardo.rb', line 7

def tardo_array_index str
  /\A\[(-?\d+)\]\Z/ =~ str ? $1.to_i : nil
end

Instance Method Details

#hash_to_paths(hash, prefix = nil) ⇒ Object



12
13
14
15
16
17
18
19
20
21
22
23
# File 'lib/nandoc/support/path-tardo.rb', line 12

def hash_to_paths hash, prefix=nil
  paths = []
  hash.each do |k,v|
    ch_prefix = [prefix, k].compact.join('/')
    if v.kind_of?(Hash)
      paths.concat hash_to_paths(v, ch_prefix)
    else
      paths.push ch_prefix
    end
  end
  paths
end

#path_tardo(hash_or_array, path_tardo, prefix = '') ⇒ 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
56
57
# File 'lib/nandoc/support/path-tardo.rb', line 25

def path_tardo hash_or_array, path_tardo, prefix = ''
  /\A([^\/]+)(?:\/(.+))?\Z/ =~ path_tardo or
    fail("no parse: #{path_tardo}")
  head, tail = $1, $2
  value = nil
  found = nil
  if idx = tardo_array_index(head)
    if idx > 0 && idx >= hash_or_array.size
      found = false
    elsif idx < 0 && (idx*-1) > hash_or_array.size
      found = false
    else
      found = true
      value = hash_or_array.slice(idx)
    end
  else
    if hash_or_array.key?(head)
      found = true
      value = hash_or_array[head]
    else
      found = false
    end
  end
  if ! found
    Tardo::NotFound.new(prefix, head, hash_or_array)
  elsif tail
    local_full_path =
      [ prefix.empty? ? nil : prefix, head ].compact.join('/')
    path_tardo(value, tail, local_full_path)
  else
    Tardo::Found.new(value)
  end
end