class Navo::StateFile
Stores persisted state.
This allows information to carry forward between different invocations of the tool, e.g. remembering a previously-started Docker container.
Public Class Methods
new(file:, logger:)
click to toggle source
# File lib/navo/state_file.rb, line 11 def initialize(file:, logger:) @file = file @logger = logger @mutex = Monitor.new end
Public Instance Methods
[](key)
click to toggle source
Access the state as if it were a hash.
@param key [String, Symbol] @return [Array, Hash, Number, String]
# File lib/navo/state_file.rb, line 21 def [](key) @mutex.synchronize do @hash[key.to_s] end end
[]=(key, value)
click to toggle source
Set the state as if it were a hash.
@param key [String, Symbol] @param value [Array, Hash, Number, String]
# 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
destroy()
click to toggle source
Destroy persisted state.
# File lib/navo/state_file.rb, line 72 def destroy @logger.debug "Removing state from #{@file}" @hash = {} FileUtils.rm_f(@file) end
load()
click to toggle source
Loads persisted state.
# 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)
click to toggle source
# 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
save()
click to toggle source
Persists state to disk.
# 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