module Gemmy::Patches::HashPatch::InstanceMethods::Persisted

Sets up a hash to mirror all changes to a database file All nested gets & sets require a list of keys, passed as subsequent args. Instead of [] and []=, use get and set

Everything in the db is contained in a hash with one predefined key, :data. The value is an empty, autovivified hash.

This also makes the caller hash autovivified

Example:

hash = {}.persisted(“db.yaml”) hash.set(:a, :b, 0) # => this writes to disk and memory hash.get(:a, :b) # => reads from memory hash.get(:a, :b, disk: true) # => reads from disk

Public Instance Methods

db() click to toggle source
# File lib/gemmy/patches/hash_patch.rb, line 330
def db
  @store
end
persisted(path) click to toggle source
# File lib/gemmy/patches/hash_patch.rb, line 313
def persisted(path)
  require 'yaml/store'
  autovivified = Gemmy.patch("hash/i/autovivified")\
                      .method(:_autovivified)
  autovivified.call(self).tap do |hash|
    # load data from YAML into memory
    hash.instance_exec do
      @store = YAML::Store.new path
      @store.transaction do
        @store[:data] ||= autovivified.call({})
        @store[:data].each { |k,v| self[k] = v.deep_dup }
      end
    end
    hash.extend Gemmy::Patches::HashPatch::PersistedHash
  end
end