module Sequel::Plugins::List::InstanceMethods
def at_position(p)
def at_position(p) list_dataset.first(position_field => p) end
def before_create
Set the value of the position_field to the maximum value plus 1 unless the
def before_create unless send(position_field) send("#{position_field}=", list_dataset.max(position_field).to_i+1) end end
def last_position
def last_position list_dataset.max(position_field).to_i end
def list_dataset
def list_dataset model.scope_proc ? model.scope_proc.call(self) : model.dataset end
def move_down(n = 1)
Move this instance down the given number of places in the list,
def move_down(n = 1) move_to(position_value + n) end
def move_to(target, lp = nil)
Move this instance to the given place in the list. Raises an
def move_to(target, lp = nil) current = position_value if target != current checked_transaction do ds = list_dataset op, ds = if target < current raise(Sequel::Error, "Moving too far up (target = #{target})") if target < 1 [:+, ds.filter(position_field=>target...current)] else lp ||= last_position raise(Sequel::Error, "Moving too far down (target = #{target}, last_position = #{lp})") if target > lp [:-, ds.filter(position_field=>(current + 1)..target)] end ds.update(position_field => Sequel::SQL::NumericExpression.new(op, position_field, 1)) update(position_field => target) end end self end
def move_to_bottom
def move_to_bottom lp = last_position move_to(lp, lp) end
def move_to_top
def move_to_top move_to(1) end
def move_up(n = 1)
Move this instance the given number of places up in the list, or 1 place
def move_up(n = 1) move_to(position_value - n) end
def next(n = 1)
The model instance the given number of places below this model instance
def next(n = 1) n == 0 ? self : at_position(position_value + n) end
def position_field
def position_field model.position_field end
def position_value
def position_value send(position_field) end
def prev(n = 1)
The model instance the given number of places below this model instance
def prev(n = 1) self.next(n * -1) end