37 lines
797 B
Ruby
37 lines
797 B
Ruby
|
# 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
|