Class: Navo::StateFile

Inherits:
Object
  • Object
show all
Defined in:
lib/navo/state_file.rb

Overview

Stores persisted state.

This allows information to carry forward between different invocations of the tool, e.g. remembering a previously-started Docker container.

Instance Method Summary collapse

Constructor Details

#initialize(file:, logger:) ⇒ StateFile

Returns a new instance of StateFile.



11
12
13
14
15
# File 'lib/navo/state_file.rb', line 11

def initialize(file:, logger:)
  @file = file
  @logger = logger
  @mutex = Monitor.new
end

Instance Method Details

#[](key) ⇒ Array, ...

Access the state as if it were a hash.

Parameters:

  • key (String, Symbol)

Returns:

  • (Array, Hash, Number, String)


21
22
23
24
25
# File 'lib/navo/state_file.rb', line 21

def [](key)
  @mutex.synchronize do
    @hash[key.to_s]
  end
end

#[]=(key, value) ⇒ Object

Set the state as if it were a hash.

Parameters:

  • key (String, Symbol)
  • value (Array, Hash, Number, String)


31
32
33
34
35
36
37
38
# File 'lib/navo/state_file.rb', line 31

def []=(key, value)
  @mutex.synchronize do
    @logger.debug "Updating state '#{key}' to #{value.inspect}"
    @hash[key.to_s] = value
    save unless @modifying
    value
  end
end

#destroyObject

Destroy persisted state.



72
73
74
75
76
# File 'lib/navo/state_file.rb', line 72

def destroy
  @logger.debug "Removing state from #{@file}"
  @hash = {}
  FileUtils.rm_f(@file)
end

#loadObject

Loads persisted state.



54
55
56
57
58
59
60
61
62
63
# File 'lib/navo/state_file.rb', line 54

def load
  @hash =
    if File.exist?(@file) && yaml = YAML.load_file(@file)
      @logger.debug "Loading state from #{@file}"
      yaml.to_hash
    else
      @logger.debug "No state file #{@file} exists; assuming empty state"
      {} # Handle empty files
    end
end

#modify(&block) ⇒ Object



40
41
42
43
44
45
46
47
48
49
50
51
# File 'lib/navo/state_file.rb', line 40

def modify(&block)
  @mutex.synchronize do
    @modifying = true
    begin
      result = block.call(self)
      save
      result
    ensure
      @modifying = false
    end
  end
end

#saveObject

Persists state to disk.



66
67
68
69
# File 'lib/navo/state_file.rb', line 66

def save
  @logger.debug "Saving state to #{@file}"
  File.open(@file, 'w') { |f| f.write(@hash.to_yaml) }
end