Move slug logic to concern

This commit is contained in:
Trevor Vallender 2024-06-12 16:13:07 +01:00
parent c01ab549fd
commit 1c2f8a5576
2 changed files with 38 additions and 23 deletions

View File

@ -0,0 +1,36 @@
# frozen_string_literal: true
module Sluggable
extend ActiveSupport::Concern
included do
validates :slug, presence: true,
length: { maximum: 100 },
uniqueness: { scope: :character_sheet_section_id }
before_validation :set_slug
private
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
end

View File

@ -1,6 +1,8 @@
# frozen_string_literal: true
class Stat < ApplicationRecord
include Sluggable
belongs_to :character_sheet_section
validates :name, presence: true,
@ -13,8 +15,6 @@ class Stat < ApplicationRecord
numericality: true
validate :validate_roll_command
before_validation :set_slug
def roll
DiceRoller.new(roll_command, stat: self).roll
end
@ -26,25 +26,4 @@ class Stat < ApplicationRecord
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