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