module MongoCollection::InstanceMethods
Public Class Methods
new(args=nil)
click to toggle source
# File lib/mongo_collection.rb, line 112 def initialize(args=nil) self.class.defaults.each do |k, v| self.send(k.to_s+"=", v) end if !args.is_a?(Hash) return end args.each do |k,v| if v == nil next end k_sym = k.to_sym k_str = k.to_s new_val = v if self.class.has_one_assosiations.has_key?(k_sym) klass = self.class.has_one_assosiations[k_sym].constantize if v.is_a?(Hash) new_val = klass.new(v) elsif !v.is_a?(klass) raise "Value should be a hash or #{klass.to_s}" end end if self.class.has_many_assosiations.has_key?(k_sym) klass = self.class.has_many_assosiations[k_sym].constantize if !v.is_a?(Array) raise "Has many assosiations should be in form of Array" end new_val = v.map do |obj| new_obj = obj if obj.is_a?(Hash) new_obj = klass.new(obj) elsif !obj.is_a?(klass) raise "Value should be a hash or #{klass.to_s}" end new_obj end end instance_variable_set "@#{k_str}", new_val if self.class.props.member?(k_sym) end end
Public Instance Methods
destroy()
click to toggle source
# File lib/mongo_collection.rb, line 163 def destroy if self.new? return false end r = self.class.collection.delete_one(_id: BSON::ObjectId(self._id)) if !self.class.after_destroy_block.nil? self.class.after_destroy_block.call(self) end r end
new?()
click to toggle source
# File lib/mongo_collection.rb, line 156 def new? if self._id.blank? return true end !BSON::ObjectId.legal?(self._id) end
save()
click to toggle source
# File lib/mongo_collection.rb, line 174 def save if !self.class.before_save_block.nil? self.class.before_save_block.call(self) end self.class.has_one_assosiations.each do |k,v| val = self.send(k) if !val next end if val.new? if !val.save raise "Unable to save assosiation #{v}" end end end self.class.has_many_assosiations.each do |k,v| val = self.send(k) if !val next end val.each do |obj| if obj.new? && !obj.save raise "Unable to save assosiation #{v}" end end end if self.new? self._id = nil result = DB[self.class.mongo_collection] .insert_one(self.class.to_bson(self)) if result.ok? self._id = result.inserted_id.to_s end ok = result.ok? else ok = DB[self.class.mongo_collection] .update_one({_id: BSON::ObjectId(self._id)}, self.class.to_bson(self)) .ok? end if ok && !self.class.after_save_block.nil? self.class.after_save_block.call(self) end ok end
to_h()
click to toggle source
# File lib/mongo_collection.rb, line 223 def to_h result = {} self.class.props.each do |prop| value = self.send(prop) if value.nil? next end if self.class.has_one_assosiations.has_key?(prop) value = value.to_h end if self.class.has_many_assosiations.has_key?(prop) value = value.map{|x| x.to_h} end result[prop] = value end return result end