tabletop-companion/app/models/concerns/sluggable.rb

37 lines
797 B
Ruby
Raw Normal View History

2024-06-12 15:13:07 +00:00
# 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