Persister   A
last analyzed

Complexity

Total Complexity 13

Size/Duplication

Total Lines 52
Duplicated Lines 0 %

Importance

Changes 1
Bugs 0 Features 0
Metric Value
c 1
b 0
f 0
dl 0
loc 52
rs 10
wmc 13

9 Methods

Rating   Name   Duplication   Size   Complexity  
A fetch() 0 3 1
A read_handle() 0 5 1
A delete() 0 6 4
A persist() 0 3 1
A save() 0 4 2
A initialize() 0 3 1
A retrieve() 0 4 1
A write_handle() 0 6 1
A expand_path() 0 3 1
1
# frozen_string_literal: true
2
3
require 'ama-entity-mapper'
4
5
require_relative '../model/account'
6
require_relative '../model/group'
7
require_relative '../model/state'
8
9
module AMA
10
  module Chef
11
    module User
12
      module State
13
        # Saves data as node attributes
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
67
    end
68
  end
69
end
70