Class: FirestoreOrm::Model
- Inherits:
-
Object
- Object
- FirestoreOrm::Model
- Defined in:
- lib/firestore_orm/model.rb
Instance Attribute Summary collapse
-
#attributes ⇒ Object
Returns the value of attribute attributes.
Class Method Summary collapse
- .collection(collection_name = nil) ⇒ Object
- .create(attributes = {}) ⇒ Object
- .find(id) ⇒ Object
- .first_or_create(conditions, attributes = {}) ⇒ Object
- .where(conditions = {}) ⇒ Object
Instance Method Summary collapse
- #delete ⇒ Object
- #id ⇒ Object
-
#initialize(attributes = {}) ⇒ Model
constructor
A new instance of Model.
- #save ⇒ Object
- #update(attributes) ⇒ Object
Constructor Details
#initialize(attributes = {}) ⇒ Model
Returns a new instance of Model.
8 9 10 |
# File 'lib/firestore_orm/model.rb', line 8 def initialize(attributes = {}) @attributes = attributes end |
Instance Attribute Details
#attributes ⇒ Object
Returns the value of attribute attributes.
6 7 8 |
# File 'lib/firestore_orm/model.rb', line 6 def attributes @attributes end |
Class Method Details
.collection(collection_name = nil) ⇒ Object
55 56 57 |
# File 'lib/firestore_orm/model.rb', line 55 def collection(collection_name = nil) @collection_name ||= collection_name || name.downcase.pluralize end |
.create(attributes = {}) ⇒ Object
49 50 51 52 53 |
# File 'lib/firestore_orm/model.rb', line 49 def create(attributes = {}) model = new(attributes) model.save model end |
.find(id) ⇒ Object
30 31 32 33 |
# File 'lib/firestore_orm/model.rb', line 30 def find(id) doc = collection_ref.document(id).get new(doc.data.merge(id: doc.document_id)) if doc.exists? end |
.first_or_create(conditions, attributes = {}) ⇒ Object
45 46 47 |
# File 'lib/firestore_orm/model.rb', line 45 def first_or_create(conditions, attributes = {}) where(conditions).first || create(attributes.merge(conditions)) end |
.where(conditions = {}) ⇒ Object
35 36 37 38 39 40 41 42 43 |
# File 'lib/firestore_orm/model.rb', line 35 def where(conditions = {}) query = collection_ref conditions.each do |field, value| query = query.where(field, '=', value) end query.get.map do |doc| new(doc.data.merge(id: doc.document_id)) end end |
Instance Method Details
#delete ⇒ Object
21 22 23 |
# File 'lib/firestore_orm/model.rb', line 21 def delete collection_ref.document(id).delete end |
#id ⇒ Object
25 26 27 |
# File 'lib/firestore_orm/model.rb', line 25 def id @attributes[:id] end |
#save ⇒ Object
12 13 14 |
# File 'lib/firestore_orm/model.rb', line 12 def save collection_ref.document(id || SecureRandom.uuid).set(@attributes) end |
#update(attributes) ⇒ Object
16 17 18 19 |
# File 'lib/firestore_orm/model.rb', line 16 def update(attributes) collection_ref.document(id).update(attributes) @attributes.merge!(attributes) end |