Move slug logic to concern
This commit is contained in:
parent
c01ab549fd
commit
1c2f8a5576
|
@ -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
|
|
@ -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
|
||||
|
|
Loading…
Reference in New Issue