Skip to content

Commit 39b0ffa

Browse files
committed
ensure that identifiers are normalized before committing to db
1 parent babdfc8 commit 39b0ffa

File tree

1 file changed

+13
-1
lines changed

1 file changed

+13
-1
lines changed

app/models/concerns/better_together/identifier.rb

Lines changed: 13 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -13,16 +13,28 @@ module Identifier
1313
unless :skip_validate_identifier? # rubocop:todo Lint/LiteralAsCondition
1414
validates :identifier,
1515
presence: true,
16-
uniqueness: true,
16+
uniqueness: { case_sensitive: false },
1717
length: { maximum: 100 }
1818
end
1919

2020
before_create :generate_identifier_slug
21+
before_validation :normalize_identifier
2122
before_validation :generate_identifier
2223
end
2324

2425
protected
2526

27+
def normalize_identifier
28+
return if identifier.blank?
29+
30+
# Downcase and replace spaces (if any) with hyphens
31+
self.identifier = identifier
32+
.downcase
33+
.gsub(/[^\w\-]/, '-') # Replace any non-word character with a hyphen
34+
.gsub(/-{2,}/, '-') # No multiple consecutive hyphens
35+
.gsub(/^[-_]+|[-_]+$/, '') # Trim leading/trailing hyphens/underscores
36+
end
37+
2638
def generate_identifier
2739
return if identifier.present?
2840

0 commit comments

Comments
 (0)