Class: Ace::Support::Items::Atoms::SlugSanitizer

Inherits:
Object
  • Object
show all
Defined in:
lib/ace/support/items/atoms/slug_sanitizer.rb

Overview

SlugSanitizer provides strict kebab-case slug sanitization for filesystem safety. Ensures consistent slug handling across the codebase.

Features:

  • Removes path traversal characters (dots, slashes, backslashes)

  • Enforces lowercase, numbers, and hyphens only

  • Collapses multiple hyphens and trims leading/trailing hyphens

  • Returns empty string for entirely invalid input (caller should handle fallback)

Constant Summary collapse

MAX_LENGTH =
55

Class Method Summary collapse

Class Method Details

.sanitize(slug, max_length: MAX_LENGTH) ⇒ String

Sanitize a slug string to strict kebab-case.

Examples:

SlugSanitizer.sanitize("My Topic-Slug")
# => "my-topic-slug"

SlugSanitizer.sanitize("../../etc/passwd")
# => "etc-passwd"

SlugSanitizer.sanitize("../")
# => "" (empty - caller should use fallback)

Parameters:

  • slug (String, nil)

    The slug to sanitize

  • max_length (Integer) (defaults to: MAX_LENGTH)

    Maximum length for the slug (default: MAX_LENGTH)

Returns:

  • (String)

    Sanitized slug (empty string if input is nil or entirely invalid)



33
34
35
36
37
38
39
40
41
42
# File 'lib/ace/support/items/atoms/slug_sanitizer.rb', line 33

def self.sanitize(slug, max_length: MAX_LENGTH)
  return "" if slug.nil? || slug.empty?

  # Remove any characters that could enable path traversal: dots, slashes, backslashes
  # Then validate against allowed pattern (lowercase, numbers, hyphens only)
  cleaned = slug.to_s.gsub(/[.\\\/]/, "").strip
  # Further sanitize to only allowed characters (lowercase letters, numbers, hyphens)
  result = cleaned.downcase.gsub(/[^a-z0-9-]/, "-").squeeze("-").gsub(/^-|-$/, "")
  truncate_at_word_boundary(result, max_length)
end