Class: RRepo::Repository

Inherits:
Object
  • Object
show all
Includes:
Abstractize
Defined in:
lib/rrepo/repository.rb

Overview

An abstract repository implementation with common functions

Instance Attribute Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(adapter) ⇒ Repository

Returns a new instance of Repository.



13
14
15
16
17
18
19
20
# File 'lib/rrepo/repository.rb', line 13

def initialize(adapter)
  @adapter = adapter
  class_name = self.class.name.demodulize
  model_class_name = class_name[/.*(?=Repository)/]
  @collection = model_class_name.underscore.pluralize.to_sym
  return if class_name == 'Repository'
  @model_class = model_class_name.constantize
end

Instance Attribute Details

#adapterObject (readonly)

Returns the value of attribute adapter.



11
12
13
# File 'lib/rrepo/repository.rb', line 11

def adapter
  @adapter
end

#collectionObject (readonly)

Returns the value of attribute collection.



11
12
13
# File 'lib/rrepo/repository.rb', line 11

def collection
  @collection
end

#model_classObject (readonly)

Returns the value of attribute model_class.



11
12
13
# File 'lib/rrepo/repository.rb', line 11

def model_class
  @model_class
end

Instance Method Details

#allObject



43
44
45
46
# File 'lib/rrepo/repository.rb', line 43

def all
  result = adapter.all(collection)
  result.map(&model_class.method(:new))
end

#clearObject



53
54
55
# File 'lib/rrepo/repository.rb', line 53

def clear
  adapter.clear(collection)
end

#create(model) ⇒ Object



22
23
24
25
26
27
# File 'lib/rrepo/repository.rb', line 22

def create(model)
  return model if model._id.present?
  id = adapter.create(collection, model)
  model._id = id
  model
end

#delete(model) ⇒ Object



36
37
38
39
40
41
# File 'lib/rrepo/repository.rb', line 36

def delete(model)
  unless model._id.present?
    fail Errors::NonPersistedModelError, "#{model} is not persisted"
  end
  adapter.delete(collection, model)
end

#find(id) ⇒ Object



48
49
50
51
# File 'lib/rrepo/repository.rb', line 48

def find(id)
  result = adapter.find(collection, id)
  model_class.new(result)
end

#update(model) ⇒ Object



29
30
31
32
33
34
# File 'lib/rrepo/repository.rb', line 29

def update(model)
  unless model._id.present?
    fail Errors::NonPersistedModelError, "#{model} is not persisted"
  end
  adapter.update(collection, model)
end