class Drum::PersistentHash

A wrapper around a hash that stores values persistently in a YAML.

@!attribute value

@return [Hash] The wrapped hash

Attributes

value[R]

Public Class Methods

new(file_path, value={}) click to toggle source

Creates a new persistent hash.

@param [String] file_path The path to the stored YAML file (may be non-existent). @param [Hash] value The initial default value, if the file doesn’t exist yet or is malformed

# File lib/drum/utils/persist.rb, line 14
def initialize(file_path, value={})
  @file_path = file_path
  begin
    self.load
  rescue StandardError => e
    @value = value
    self.store
  end
end

Public Instance Methods

[](key) click to toggle source

Reads a mapping from the hash.

@param [Object] key The key to use. @return [Object] The value the key is mapped to.

# File lib/drum/utils/persist.rb, line 47
def [](key)
  @value[key]
end
[]=(key, value) click to toggle source

Writes a mapping to the hash and stores it on disk.

@param [Object] key The key to use. @param [Object] value The value to map the key to.

# File lib/drum/utils/persist.rb, line 38
def []=(key, value)
  @value[key] = value
  store
end
load() click to toggle source

Loads the hash from the file.

# File lib/drum/utils/persist.rb, line 25
def load
  @value = YAML.load(File.read(@file_path))
end
store() click to toggle source

Saves the hash to the file.

# File lib/drum/utils/persist.rb, line 30
def store
  File.write(@file_path, @value.to_yaml)
end