51 lines
1.1 KiB
Ruby
51 lines
1.1 KiB
Ruby
# frozen_string_literal: true
|
|
|
|
class Stat < ApplicationRecord
|
|
belongs_to :character_sheet_section
|
|
|
|
validates :name, presence: true,
|
|
length: { maximum: 100 },
|
|
uniqueness: { scope: :character_sheet_section_id }
|
|
validates :slug, presence: true,
|
|
length: { maximum: 100 },
|
|
uniqueness: true
|
|
validates :value, presence: true,
|
|
numericality: true
|
|
validate :validate_roll_command
|
|
|
|
before_validation :set_slug
|
|
|
|
def roll
|
|
DiceRoller.new(roll_command, stat: self).roll
|
|
end
|
|
|
|
private
|
|
|
|
def validate_roll_command
|
|
return if roll_command.blank?
|
|
|
|
DiceRoller.new(roll_command).valid?
|
|
end
|
|
|
|
def set_slug
|
|
return if slug.present? || name.blank?
|
|
|
|
slug = if character_sheet_section.parent_section.present?
|
|
[
|
|
character_sheet_section.parent_section.name.parameterize,
|
|
name.parameterize,
|
|
].join("-")
|
|
else
|
|
slug = name.parameterize
|
|
end
|
|
|
|
suffix = 2
|
|
while Stat.exists?(slug:)
|
|
slug = "#{slug}-#{suffix}"
|
|
suffix += 1
|
|
end
|
|
|
|
self.slug = slug
|
|
end
|
|
end
|