Sha256: d0f0557beef729a992a3fcadc03a4fe7c679cb8ad406c53ee9e925196fb08068

Contents?: true

Size: 972 Bytes

Versions: 1

Compression:

Stored size: 972 Bytes

Contents

require 'sequel'
require_relative 'mapper'

module Kamerling
  class Repo
    NotFound = Class.new(RuntimeError)

    def initialize(klass, source, mapper: Mapper)
      @klass  = klass
      @mapper = mapper
      @source = source
    end

    def <<(object)
      hash = mapper.to_h(object)
      warn_off { source << hash }
    rescue Sequel::UniqueConstraintViolation
      warn_off { source.where(uuid: object.uuid).update hash }
    end

    def [](uuid)
      hash = warn_off { source[uuid: uuid] }
      fail NotFound, "#{klass} with UUID #{uuid}" unless hash
      mapper.from_h(klass, hash)
    end

    def all
      source.all.map { |hash| mapper.from_h(klass, hash) }
    end

    def related_to(object)
      key = "#{object.class.name.split('::').last.downcase}_uuid".to_sym
      source.where(key => object.uuid).map { |hash| mapper.from_h(klass, hash) }
    end

    attr_reader :klass, :mapper, :source
    private     :klass, :mapper, :source
  end
end

Version data entries

1 entries across 1 versions & 1 rubygems

Version Path
kamerling-0.0.3 lib/kamerling/repo.rb