Module: StateMate::Adapters::JSON

Defined in:
lib/state_mate/adapters/json.rb

Class Method Summary collapse

Class Method Details

.parse_key(key) ⇒ Object



7
8
9
10
# File 'lib/state_mate/adapters/json.rb', line 7

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

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



12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
# File 'lib/state_mate/adapters/json.rb', line 12

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

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

  value = JSON.load contents

  key_segs.each do |seg|
    value = if (value.is_a?(Hash) && value.key?(seg))
      value[seg]
    else
      nil
    end
  end

  value
end

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



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
58
59
60
# File 'lib/state_mate/adapters/json.rb', line 30

def self.write key, value, options = {}
  options = {
    'pretty' => true,
  }.merge options

  filepath, key_segs = parse_key key

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

    StateMate::Adapters::Defaults.hash_deep_write!(
      root,
      key_segs,
      value
    )

    root
  else
    value
  end

  content = if options['pretty']
    JSON.pretty_generate new_root
  else
    JSON.dump new_root
  end

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