2018-11-18 11:00:15 +05:30
|
|
|
# frozen_string_literal: true
|
|
|
|
|
2016-09-13 17:45:13 +05:30
|
|
|
module Boards
|
|
|
|
module Lists
|
2018-03-17 18:26:18 +05:30
|
|
|
class MoveService < Boards::BaseService
|
2016-09-13 17:45:13 +05:30
|
|
|
def execute(list)
|
2016-11-03 12:29:30 +05:30
|
|
|
@board = list.board
|
2016-09-13 17:45:13 +05:30
|
|
|
@old_position = list.position
|
|
|
|
@new_position = params[:position]
|
|
|
|
|
|
|
|
return false unless list.movable?
|
|
|
|
return false unless valid_move?
|
|
|
|
|
|
|
|
list.with_lock do
|
|
|
|
reorder_intermediate_lists
|
|
|
|
update_list_position(list)
|
|
|
|
end
|
|
|
|
end
|
|
|
|
|
|
|
|
private
|
|
|
|
|
2016-11-03 12:29:30 +05:30
|
|
|
attr_reader :board, :old_position, :new_position
|
2016-09-13 17:45:13 +05:30
|
|
|
|
|
|
|
def valid_move?
|
|
|
|
new_position.present? && new_position != old_position &&
|
|
|
|
new_position >= 0 && new_position < board.lists.movable.size
|
|
|
|
end
|
|
|
|
|
|
|
|
def reorder_intermediate_lists
|
|
|
|
if old_position < new_position
|
|
|
|
decrement_intermediate_lists
|
|
|
|
else
|
|
|
|
increment_intermediate_lists
|
|
|
|
end
|
|
|
|
end
|
|
|
|
|
2018-12-05 23:21:45 +05:30
|
|
|
# rubocop: disable CodeReuse/ActiveRecord
|
2016-09-13 17:45:13 +05:30
|
|
|
def decrement_intermediate_lists
|
|
|
|
board.lists.movable.where('position > ?', old_position)
|
|
|
|
.where('position <= ?', new_position)
|
|
|
|
.update_all('position = position - 1')
|
|
|
|
end
|
2018-12-05 23:21:45 +05:30
|
|
|
# rubocop: enable CodeReuse/ActiveRecord
|
2016-09-13 17:45:13 +05:30
|
|
|
|
2018-12-05 23:21:45 +05:30
|
|
|
# rubocop: disable CodeReuse/ActiveRecord
|
2016-09-13 17:45:13 +05:30
|
|
|
def increment_intermediate_lists
|
|
|
|
board.lists.movable.where('position >= ?', new_position)
|
|
|
|
.where('position < ?', old_position)
|
|
|
|
.update_all('position = position + 1')
|
|
|
|
end
|
2018-12-05 23:21:45 +05:30
|
|
|
# rubocop: enable CodeReuse/ActiveRecord
|
2016-09-13 17:45:13 +05:30
|
|
|
|
|
|
|
def update_list_position(list)
|
|
|
|
list.update_attribute(:position, new_position)
|
|
|
|
end
|
|
|
|
end
|
|
|
|
end
|
|
|
|
end
|