tabletop-companion/app/models/character_sheet_feature.rb

70 lines
1.9 KiB
Ruby
Raw Normal View History

2024-06-17 13:53:09 +00:00
# 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 }
2024-06-17 13:53:09 +00:00
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
unless character_sheet_section.character_sheet_features.exists?(order_index: to)
update!(order_index: to)
return
end
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
2024-06-17 13:53:09 +00:00
private
def set_order_index
return if order_index.present?
2024-06-17 13:53:09 +00:00
if character_sheet_section.character_sheet_features.any?
2024-06-19 15:42:15 +00:00
self.order_index = character_sheet_section.character_sheet_features.order(:order_index).last.order_index + 1
2024-06-17 13:53:09 +00:00
else
self.order_index = 1
2024-06-17 13:53:09 +00:00
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