# frozen_string_literal: true class CharacterSheetFeature < ApplicationRecord belongs_to :character_sheet_section belongs_to :featurable, polymorphic: true validates :order_index, presence: true, numericality: { only_integer: true, greater_than: 0 }, uniqueness: { scope: :character_sheet_section_id } validates :slug, presence: true, length: { maximum: 100 }, uniqueness: { scope: :character_sheet_section_id } before_validation :set_slug before_validation :set_order_index def move(to:) return if to == order_index return if to < character_sheet_section.lowest_order_index || to > character_sheet_section.highest_order_index if to < order_index character_sheet_section.character_sheet_features.where(order_index: to...order_index) .update_all("order_index = order_index + 1") else character_sheet_section.character_sheet_features.where(order_index: (order_index+1)..to) .update_all("order_index = order_index - 1") end update!(order_index: to) end private def set_order_index return if order_index.present? if character_sheet_section.character_sheet_features.any? self.order_index = character_sheet_section.character_sheet_features.order(:order_index).last.order_index + 1 else self.order_index = 1 end end def set_slug return if slug.present? || featurable.name.blank? slug = if character_sheet_section.parent_section.present? [ character_sheet_section.parent_section.name.parameterize, featurable.name.parameterize, ].join("-") else slug = featurable.name.parameterize end suffix = 2 while CharacterSheetFeature.exists?(slug:) slug = "#{slug}-#{suffix}" suffix += 1 end self.slug = slug end end