Class: Kybus::Storage::Datasource::Repository

Inherits:
Object
  • Object
show all
Includes:
Exceptions
Defined in:
lib/kybus/storage/datasource/repository.rb

Overview

Base class for repositories. The ID generator might get deprecated. It provides the interface for storing objects inside any persistance provider implemented. TODO: Find a better strategy for primary key handling.

Direct Known Subclasses

JSONRepository

Instance Method Summary collapse

Constructor Details

#initialize(id, id_generator) ⇒ Repository

Returns a new instance of Repository.



14
15
16
17
# File 'lib/kybus/storage/datasource/repository.rb', line 14

def initialize(id, id_generator)
  @id = id
  @id_generator = id_generator
end

Instance Method Details

#create(id = nil) ⇒ Object



27
28
29
30
31
32
33
# File 'lib/kybus/storage/datasource/repository.rb', line 27

def create(id = nil)
  data = create_initial_object(id)
  existent = exist?(data[@id])
  raise(ObjectAlreadyExists.new(data[@id], existent)) if existent

  create_(data)
end

#create_initial_object(id) ⇒ Object



19
20
21
22
23
24
25
# File 'lib/kybus/storage/datasource/repository.rb', line 19

def create_initial_object(id)
  return id if @id.nil? && id.is_a?(Hash)

  object = { @id => @id_generator.call(id, @id) }
  object.merge!(id) if id.is_a?(Hash)
  object
end

#exist?(id) ⇒ Boolean

Returns:

  • (Boolean)


35
36
37
38
39
40
41
42
43
# File 'lib/kybus/storage/datasource/repository.rb', line 35

def exist?(id)
  # Not the better solution, but works for objects that don't contain
  # a unique id.
  return false if id.nil?

  get(id)
rescue ObjectNotFound
  nil
end