Sha256: 1bf502d266e110e8fb140e1ea123106862197bfd9c1fa07216648880adffa79a

Contents?: true

Size: 1.1 KB

Versions: 4

Compression:

Stored size: 1.1 KB

Contents

require 'donjon/encrypted_file'
require 'json'

module Donjon
  class Database
    def initialize(actor:)
      @actor = actor
    end

    def [](key)
      file = _file(key)
      return unless file.readable? 
      _key, value = _unpack(file.read)
      assert(key == _key, "bad stored data for #{key}!")
      return value
    end

    def []=(key, value)
      _file(key).write(_pack(key, value))
    end

    def each
      parent = @actor.repo.join('data')
      return unless parent.exist?
      parent.children.each do |child|
        path = "data/#{child.basename}"
        file = EncryptedFile.new(path: path, actor: @actor)
        next unless file.readable?
        yield *_unpack(file.read)
      end
    end

    def update
      each do |key, value|
        self[key] = value
      end
      nil
    end


    private

    def _pack(key, value)
      JSON.dump([key, value])
    end

    def _unpack(data)
      JSON.parse(data)
    end

    def _hash(key)
      OpenSSL::Digest::SHA256.hexdigest(key)
    end

    def _file(key)
      EncryptedFile.new(path: "data/#{_hash(key)}", actor: @actor)
    end
  end
end

Version data entries

4 entries across 4 versions & 1 rubygems

Version Path
donjon-0.0.4 lib/donjon/database.rb
donjon-0.0.3 lib/donjon/database.rb
donjon-0.0.2 lib/donjon/database.rb
donjon-0.0.1 lib/donjon/database.rb