12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273 |
- module CanPriorization
- extend ActiveSupport::Concern
- included do
- before_create :fill_prio
- before_update :rearrangement
- end
- def rearrangement
-
- return true if !changes['prio']
- rearranged_prio = 0
- rearrangement_previous_ordered_ids.each do |entry_id|
-
- next if id == entry_id
- rearranged_prio += 1
-
-
- if rearranged_prio == prio
- rearranged_prio += 1
- end
- rearrange_entry(entry_id, rearranged_prio)
- end
- end
- def fill_prio
- return true if prio.present?
- self.prio = self.class.calculate_prio
- true
- end
- def rearrangement_previous_ordered_ids
- self.class.reorder(
- prio: :asc,
- updated_at: :desc
- ).pluck(:id)
- end
- def rearrange_entry(id, prio)
-
- self.class.without_callback(:update, :before, :rearrangement) do
-
- entry = self.class.where(
- id: id
- ).where.not(
- prio: prio
- ).take
- next if entry.blank?
- entry.update!(prio: prio)
- end
- end
-
- class_methods do
- def calculate_prio
- existing_maximum = maximum(:prio)
- return 0 if !existing_maximum
- existing_maximum + 1
- end
- end
- end
|