Total Complexity | 13 |
Total Lines | 52 |
Duplicated Lines | 0 % |
Changes | 1 | ||
Bugs | 0 | Features | 0 |
1 | # frozen_string_literal: true |
||
14 | class Persister |
||
15 | attr_reader :node |
||
16 | |||
17 | # @param [Chef::Node] node |
||
18 | def initialize(node) |
||
19 | @node = node |
||
20 | end |
||
21 | |||
22 | def retrieve(context_name) |
||
23 | data = fetch(context_name) || {} |
||
24 | Entity::Mapper.map(data, AMA::Chef::User::Model::State) |
||
25 | end |
||
26 | |||
27 | def persist(context_name, state) |
||
28 | save([context_name], Entity::Mapper.normalize(state)) |
||
29 | end |
||
30 | |||
31 | private |
||
32 | |||
33 | def save(path, data) |
||
34 | data = data.normalize if data.respond_to? :normalize |
||
35 | write_handle(*path[0..-2])[path[-1]] = data |
||
36 | end |
||
37 | |||
38 | def fetch(*path) |
||
39 | read_handle(*path) |
||
40 | end |
||
41 | |||
42 | def delete(*path) |
||
43 | return if path.empty? |
||
44 | path = [path] if path.is_a?(String) |
||
45 | return if read_handle(path).nil? |
||
46 | write_handle(path[0..-2]).delete(path[-1]) |
||
47 | end |
||
48 | |||
49 | def expand_path(*path) |
||
50 | %w[ama user state].push(*path) |
||
51 | end |
||
52 | |||
53 | def read_handle(*path) |
||
54 | expand_path(*path).reduce(node) do |cursor, segment| |
||
55 | cursor && cursor.key?(segment) ? cursor[segment] : nil |
||
56 | end |
||
57 | end |
||
58 | |||
59 | def write_handle(*path) |
||
60 | expand_path(*path).reduce(node.normal) do |cursor, segment| |
||
61 | cursor[segment] = {} unless cursor.key?(segment) |
||
62 | cursor[segment] |
||
63 | end |
||
64 | end |
||
65 | end |
||
66 | end |
||
70 |