Class: Kamerling::Repo

Inherits:
Object
  • Object
show all
Defined in:
lib/kamerling/repo.rb

Constant Summary collapse

NotFound =
Class.new(RuntimeError)

Instance Method Summary collapse

Constructor Details

#initialize(klass, source, mapper: Mapper) ⇒ Repo

Returns a new instance of Repo.



8
9
10
11
12
# File 'lib/kamerling/repo.rb', line 8

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

Instance Method Details

#<<(object) ⇒ Object



14
15
16
17
18
19
# File 'lib/kamerling/repo.rb', line 14

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

#[](uuid) ⇒ Object



21
22
23
24
25
# File 'lib/kamerling/repo.rb', line 21

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

#allObject



27
28
29
# File 'lib/kamerling/repo.rb', line 27

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


31
32
33
34
# File 'lib/kamerling/repo.rb', line 31

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