Skip to content

Make next fields optional #21

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Open
wants to merge 4 commits into
base: master
Choose a base branch
from
Open
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
10 changes: 9 additions & 1 deletion lib/resort.rb
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down Expand Up @@ -142,6 +142,7 @@ def siblings
# empty list.
def include_in_list!
self.class.transaction do
save
lock!
_siblings.count > 0 ? last!\
: prepend
Expand All @@ -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
Expand All @@ -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
Expand All @@ -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)
Expand All @@ -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
Expand All @@ -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?
Expand Down