Class: Holoserve::Tool::DataPath

Inherits:
Object
  • Object
show all
Defined in:
lib/holoserve/tool/data_path.rb

Constant Summary collapse

PATH_SEPARATOR =
".".freeze

Instance Attribute Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(path, data) ⇒ DataPath

Returns a new instance of DataPath.



9
10
11
# File 'lib/holoserve/tool/data_path.rb', line 9

def initialize(path, data)
  self.path, self.data = path, data
end

Instance Attribute Details

#dataObject

Returns the value of attribute data.



7
8
9
# File 'lib/holoserve/tool/data_path.rb', line 7

def data
  @data
end

#pathObject

Returns the value of attribute path.



6
7
8
# File 'lib/holoserve/tool/data_path.rb', line 6

def path
  @path
end

Instance Method Details

#fetchObject



17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
# File 'lib/holoserve/tool/data_path.rb', line 17

def fetch
  path = @path ? @path.split(PATH_SEPARATOR) : [ ]
  return @data if path.empty?

  selected = @data
  key = parse_key path.shift

  while path.length > 0
    return nil unless selected.respond_to?(:[])
    selected = selected[key]

    key = parse_key path.shift
  end

  return nil unless selected.respond_to?(:[])
  selected[key]
end

#store(value) ⇒ Object



35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
# File 'lib/holoserve/tool/data_path.rb', line 35

def store(value)
  path = @path ? @path.split(PATH_SEPARATOR) : [ ]
  return Holoserve::Tool::Merger.new(@data, value).result if path.empty?

  result = selected = clone(@data)
  key = parse_key path.shift

  while path.length > 0
    break unless selected.respond_to?(:[])

    selected[key] ||= path.first.to_s == "@" ? [ ] : { }
    selected = selected[key]
    key = parse_key path.shift
  end

  key = selected.length if key.to_s == "@"

  selected[key] = value
  result
end