Module: StateMate::Adapters::YAML

Includes:
StateMate::Adapters
Defined in:
lib/state_mate/adapters/yaml.rb

Constant Summary

Constants included from StateMate::Adapters

API_METHOD_NAMES, DEFAULT_KEY_SEP

Class Method Summary collapse

Methods included from StateMate::Adapters

get, included, register

Class Method Details

.cast_seg(key_seg) ⇒ Object



22
23
24
25
26
27
28
# File 'lib/state_mate/adapters/yaml.rb', line 22

def self.cast_seg key_seg
  if key_seg =~ /\A[0-9]+\z/
    key_seg.to_i
  else
    key_seg
  end
end

.deep_write!(obj, key_segs, value) ⇒ Object



73
74
75
76
77
78
79
80
81
82
83
84
# File 'lib/state_mate/adapters/yaml.rb', line 73

def self.deep_write! obj, key_segs, value
  seg = cast_seg key_segs.first
  rest = key_segs[1..-1]
  
  if rest.empty?
    obj[seg] = value
    
  else
    deep_write! obj[seg], rest, value
    
  end
end

.parse_key(key) ⇒ Object



17
18
19
20
# File 'lib/state_mate/adapters/yaml.rb', line 17

def self.parse_key key
  # use the same key seperation as Defaults
  StateMate::Adapters::Defaults.parse_key key
end

.preorder=(keys) ⇒ Object



13
14
15
# File 'lib/state_mate/adapters/yaml.rb', line 13

def self.preorder= keys
  @preorder = keys
end

.read(key, options = {}) ⇒ Object



30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
# File 'lib/state_mate/adapters/yaml.rb', line 30

def self.read key, options = {}
  filepath, key_segs = parse_key key

  contents = File.read(File.expand_path(filepath))

  value = ::YAML.load contents

  key_segs.each do |seg|
    seg = cast_seg seg
    
    value = case value
    when Hash, Array
      value = value[seg]
    else
      nil
    end
  end

  value
end

.write(key, value, options = {}) ⇒ Object



51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
# File 'lib/state_mate/adapters/yaml.rb', line 51

def self.write key, value, options = {}
  StateMate.debug key: key, value: value, options: options
  
  filepath, key_segs = parse_key key

  new_root = if key_segs.length > 1
    root = read filepath

    deep_write! root, key_segs, value

    root
  else
    value
  end

  content = DiffableYAML.dump new_root, preorder: @preorder

  File.open(filepath, 'w') do |f|
    f.write content
  end
end