Module: Gemmy::Patches::HashPatch::InstanceMethods::Persisted

Defined in:
lib/gemmy/patches/hash_patch.rb

Overview

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

Instance Method Summary collapse

Instance Method Details

#dbObject



330
331
332
# File 'lib/gemmy/patches/hash_patch.rb', line 330

def db
  @store
end

#persisted(path) ⇒ Object



313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
# 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