discourse/lib/concern/positionable.rb

40 lines
1.1 KiB
Ruby
Raw Normal View History

2013-10-18 15:09:30 +08:00
module Concern
module Positionable
extend ActiveSupport::Concern
def move_to(position_arg)
2013-10-18 15:09:30 +08:00
position = [[position_arg, 0].max, self.class.count - 1].min
2013-10-21 13:14:09 +08:00
if self.position.nil? or position > self.position
self.exec_sql "
UPDATE #{self.class.table_name}
SET position = position - 1
WHERE position > :current_position and position <= :new_position",
{current_position: self.position, new_position: position}
elsif position < self.position
self.exec_sql "
UPDATE #{self.class.table_name}
SET position = position + 1
WHERE position >= :new_position and position < :current_position",
{current_position: self.position, new_position: position}
else
# Not moving to a new position
return
end
2013-10-21 13:14:09 +08:00
2013-10-18 15:09:30 +08:00
self.exec_sql "
UPDATE #{self.class.table_name}
SET position = :position
WHERE id = :id", {id: id, position: position}
end
2013-10-18 15:09:30 +08:00
def use_default_position
2013-10-18 15:09:30 +08:00
self.exec_sql "
UPDATE #{self.class.table_name}
SET POSITION = null
WHERE id = :id", {id: id}
2013-10-18 15:09:30 +08:00
end
end
end