tabletop-companion/app/models/character_sheet_feature.rb

50 lines
1.2 KiB
Ruby

# frozen_string_literal: true
class CharacterSheetFeature < ApplicationRecord
belongs_to :character_sheet_section
belongs_to :featurable, polymorphic: true
validates :order, presence: true,
numericality: { only_integer: true, greater_than: 0 }
validates :slug, presence: true,
length: { maximum: 100 },
uniqueness: { scope: :character_sheet_section_id }
before_validation :set_slug
before_validation :set_order
private
def set_order
return if order.present?
if character_sheet_section.character_sheet_features.any?
self.order = character_sheet_section.character_sheet_features.order(:order).last.order + 1
else
self.order = 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