Module: StateMate::Adapters::JSON
Constant Summary
API_METHOD_NAMES, DEFAULT_KEY_SEP
Class Method Summary
collapse
get, included, register
Class Method Details
.read(key, options = {}) ⇒ Object
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
|
# File 'lib/state_mate/adapters/json.rb', line 15
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
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
61
62
63
64
65
66
67
68
69
70
|
# File 'lib/state_mate/adapters/json.rb', line 33
def self.write key, value, options = {}
options = {
'pretty' => true,
}.merge options
filepath, key_segs = parse_key key
StateMate.debug "writing json",
options: options,
filepath: filepath,
key_segs: key_segs
new_root = if key_segs.empty?
value
else
root = read filepath
StateMate::Adapters::Defaults.hash_deep_write!(
root,
key_segs,
value
)
root
end
StateMate.debug new_root: new_root
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
|