Class: RRepo::Repository
- Inherits:
-
Object
- Object
- RRepo::Repository
- Includes:
- Abstractize
- Defined in:
- lib/rrepo/repository.rb
Overview
An abstract repository implementation with common functions
Instance Attribute Summary collapse
-
#adapter ⇒ Object
readonly
Returns the value of attribute adapter.
-
#collection ⇒ Object
readonly
Returns the value of attribute collection.
-
#model_class ⇒ Object
readonly
Returns the value of attribute model_class.
Instance Method Summary collapse
- #all ⇒ Object
- #clear ⇒ Object
- #create(model) ⇒ Object
- #delete(model) ⇒ Object
- #find(id) ⇒ Object
-
#initialize(adapter) ⇒ Repository
constructor
A new instance of Repository.
- #update(model) ⇒ Object
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
#adapter ⇒ Object (readonly)
Returns the value of attribute adapter.
11 12 13 |
# File 'lib/rrepo/repository.rb', line 11 def adapter @adapter end |
#collection ⇒ Object (readonly)
Returns the value of attribute collection.
11 12 13 |
# File 'lib/rrepo/repository.rb', line 11 def collection @collection end |
#model_class ⇒ Object (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
#all ⇒ Object
43 44 45 46 |
# File 'lib/rrepo/repository.rb', line 43 def all result = adapter.all(collection) result.map(&model_class.method(:new)) end |
#clear ⇒ Object
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 |