2018-07-16 12:31:01 -04:00
|
|
|
# frozen_string_literal: true
|
|
|
|
|
2016-07-27 19:33:22 -04:00
|
|
|
module Boards
|
|
|
|
module Lists
|
2017-08-31 13:48:57 -04:00
|
|
|
class MoveService < Boards::BaseService
|
2016-08-16 00:07:25 -04:00
|
|
|
def execute(list)
|
2016-10-05 13:13:43 -04:00
|
|
|
@board = list.board
|
2016-08-16 00:07:25 -04:00
|
|
|
@old_position = list.position
|
|
|
|
@new_position = params[:position]
|
|
|
|
|
2016-08-16 13:38:43 -04:00
|
|
|
return false unless list.movable?
|
2016-07-28 18:26:16 -04:00
|
|
|
return false unless valid_move?
|
2016-07-27 19:33:22 -04:00
|
|
|
|
|
|
|
list.with_lock do
|
|
|
|
reorder_intermediate_lists
|
2016-08-16 00:07:25 -04:00
|
|
|
update_list_position(list)
|
2016-07-27 19:33:22 -04:00
|
|
|
end
|
|
|
|
end
|
|
|
|
|
|
|
|
private
|
|
|
|
|
2016-10-05 13:13:43 -04:00
|
|
|
attr_reader :board, :old_position, :new_position
|
2016-07-27 19:33:22 -04:00
|
|
|
|
2016-07-28 18:26:16 -04:00
|
|
|
def valid_move?
|
|
|
|
new_position.present? && new_position != old_position &&
|
2016-08-16 13:38:43 -04:00
|
|
|
new_position >= 0 && new_position < board.lists.movable.size
|
2016-07-28 01:20:23 -04:00
|
|
|
end
|
|
|
|
|
2016-07-27 19:33:22 -04:00
|
|
|
def reorder_intermediate_lists
|
|
|
|
if old_position < new_position
|
2016-07-28 01:20:23 -04:00
|
|
|
decrement_intermediate_lists
|
2016-07-27 19:33:22 -04:00
|
|
|
else
|
2016-07-28 01:20:23 -04:00
|
|
|
increment_intermediate_lists
|
2016-07-27 19:33:22 -04:00
|
|
|
end
|
|
|
|
end
|
|
|
|
|
2018-08-27 11:31:01 -04:00
|
|
|
# rubocop: disable CodeReuse/ActiveRecord
|
2016-07-28 01:20:23 -04:00
|
|
|
def decrement_intermediate_lists
|
2016-08-16 13:38:43 -04:00
|
|
|
board.lists.movable.where('position > ?', old_position)
|
|
|
|
.where('position <= ?', new_position)
|
|
|
|
.update_all('position = position - 1')
|
2016-07-28 01:20:23 -04:00
|
|
|
end
|
2018-08-27 11:31:01 -04:00
|
|
|
# rubocop: enable CodeReuse/ActiveRecord
|
2016-07-28 01:20:23 -04:00
|
|
|
|
2018-08-27 11:31:01 -04:00
|
|
|
# rubocop: disable CodeReuse/ActiveRecord
|
2016-07-28 01:20:23 -04:00
|
|
|
def increment_intermediate_lists
|
2016-08-16 13:38:43 -04:00
|
|
|
board.lists.movable.where('position >= ?', new_position)
|
|
|
|
.where('position < ?', old_position)
|
|
|
|
.update_all('position = position + 1')
|
2016-07-28 01:20:23 -04:00
|
|
|
end
|
2018-08-27 11:31:01 -04:00
|
|
|
# rubocop: enable CodeReuse/ActiveRecord
|
2016-07-28 01:20:23 -04:00
|
|
|
|
2016-08-16 00:07:25 -04:00
|
|
|
def update_list_position(list)
|
2016-07-27 19:33:22 -04:00
|
|
|
list.update_attribute(:position, new_position)
|
|
|
|
end
|
|
|
|
end
|
|
|
|
end
|
|
|
|
end
|