diff --git a/lib/resort.rb b/lib/resort.rb index 9a8518c..b66e235 100644 --- a/lib/resort.rb +++ b/lib/resort.rb @@ -62,7 +62,7 @@ def included(base) base.send :include, InstanceMethods base.has_one :previous, class_name: base.name, foreign_key: 'next_id', inverse_of: :next - base.belongs_to :next, class_name: base.name, inverse_of: :previous + base.belongs_to :next, class_name: base.name, inverse_of: :previous, optional: true base.after_create :include_in_list! base.after_destroy :delete_from_list @@ -142,6 +142,7 @@ def siblings # empty list. def include_in_list! self.class.transaction do + save lock! _siblings.count > 0 ? last!\ : prepend @@ -151,6 +152,7 @@ def include_in_list! # Puts the object in the first position of the list. def prepend self.class.transaction do + save lock! return if first? if _siblings.count > 0 @@ -166,6 +168,7 @@ def prepend # Puts the object in the last position of the list. def push self.class.transaction do + save lock! append_to(_siblings.last_in_order) unless last? end @@ -174,8 +177,10 @@ def push # Puts the object right after another object in the list. def append_to(another) self.class.transaction do + save lock! return if another.next_id == id + another.save another.lock! delete_from_list if next_id || (another && another.next_id) @@ -193,6 +198,7 @@ def last? def last! self.class.transaction do + save lock! raise(ActiveRecord::RecordNotSaved) unless _siblings.last_in_order.update_attribute(:next_id, id) end @@ -202,9 +208,11 @@ def last! def delete_from_list if first? && self.next + self.next.save self.next.lock! raise(ActiveRecord::RecordNotSaved) unless self.next.update_attribute(:first, true) elsif previous + previous.save previous.lock! p = previous self.previous = nil unless frozen?