Sha256: df8ede0db008ae120e626753a51db99dba62c6d6d53dda68583f93d9305ce86b

Contents?: true

Size: 1.23 KB

Versions: 4

Compression:

Stored size: 1.23 KB

Contents

# frozen_string_literal: true

module Basketball
  module App
    # Base class for all repositories which are based on a flat document.
    # At the very minimum sub-classes should implement #to_h(object) and #from_h(hash).
    class DocumentRepository
      attr_reader :store

      def initialize(store = InMemoryStore.new)
        super()

        @store = store
      end

      def load(id)
        contents = store.read(id)

        deserialize(contents).tap do |object|
          object.send('id=', id)
        end
      end

      def save(id, object)
        object.send('id=', id)

        contents = serialize(object)

        store.write(id, contents)

        object
      end

      def delete(object)
        return false unless object.id

        store.delete(object.id)

        object.send('id=', nil)

        true
      end

      def exist?(id)
        store.exist?(id)
      end

      protected

      def from_h(hash)
        Entity.new(hash[:id])
      end

      def to_h(entity)
        { id: entity.id }
      end

      private

      def deserialize(string)
        hash = JSON.parse(string, symbolize_names: true)

        from_h(hash)
      end

      def serialize(object)
        to_h(object).to_json
      end
    end
  end
end

Version data entries

4 entries across 4 versions & 1 rubygems

Version Path
basketball-0.0.17 lib/basketball/app/document_repository.rb
basketball-0.0.16 lib/basketball/app/document_repository.rb
basketball-0.0.15 lib/basketball/app/document_repository.rb
basketball-0.0.14 lib/basketball/app/document_repository.rb