Class: Navo::StateFile
- Inherits:
-
Object
- Object
- Navo::StateFile
- 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
-
#[](key) ⇒ Array, ...
Access the state as if it were a hash.
-
#[]=(key, value) ⇒ Object
Set the state as if it were a hash.
-
#destroy ⇒ Object
Destroy persisted state.
-
#initialize(file:, logger:) ⇒ StateFile
constructor
A new instance of StateFile.
-
#load ⇒ Object
Loads persisted state.
- #modify(&block) ⇒ Object
-
#save ⇒ Object
Persists state to disk.
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.
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.
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 |
#destroy ⇒ Object
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 |
#load ⇒ Object
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 |
#save ⇒ Object
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 |