lib/ohm.rb in ohm-0.0.17 vs lib/ohm.rb in ohm-0.0.18

- old
+ new

@@ -383,35 +383,49 @@ end end def initialize(attrs = {}) @_attributes = Hash.new {|hash,key| hash[key] = read_remote(key) } - - attrs.each do |key, value| - send(:"#{key}=", value) - end + update_attributes(attrs) end def new? !id end def create return unless valid? initialize_id - create_model_membership - add_to_indices - save! + + mutex do + create_model_membership + add_to_indices + save! + end end def save return create if new? return unless valid? - update_indices - save! + + mutex do + update_indices + save! + end end + def update(attrs) + update_attributes(attrs) + save + end + + def update_attributes(attrs) + attrs.each do |key, value| + send(:"#{key}=", value) + end + end + def delete delete_from_indices delete_attributes(attributes) delete_attributes(counters) delete_attributes(collections) @@ -455,10 +469,18 @@ other.key == key rescue ModelIsNew false end + # Lock the object before ejecuting the block, and release it once the block is done. + def mutex + lock! + yield + unlock! + self + end + protected def key(*args) raise ModelIsNew if new? self.class.key(id, *args) @@ -550,8 +572,20 @@ end end def index_key_for(attrs, values) self.class.key *(attrs + self.class.encode_each(values)) + end + + # Lock the object so no other instances can modify it. + # @see Model#mutex + def lock! + lock = db.setnx(key(:_lock), 1) until lock == 1 + end + + # Release the lock. + # @see Model#mutex + def unlock! + db.del(key(:_lock)) end end end