Class: Openphar::Core::SlugGenerator
- Inherits:
-
Object
- Object
- Openphar::Core::SlugGenerator
- Defined in:
- lib/openphar/core/slug_generator.rb
Overview
Unified slug generator for consistent URL-safe identifier generation.
Consolidates multiple slug generation implementations into a single class. All slugs are lowercase, hyphen-separated, and contain only alphanumeric characters and hyphens.
Constant Summary collapse
- DEFAULT_SLUG =
Default slug for nil/empty inputs
'unknown'
Class Method Summary collapse
-
.generate(name) ⇒ String
Generate a URL-safe slug from any name.
-
.generate_from_title(title) ⇒ String
Generate a slug from a title with potential English and Latin parts.
-
.generate_latin(latin_name) ⇒ String
Generate a slug optimized for Latin pharmaceutical names.
-
.generate_unique(name, existing_slugs) ⇒ String
Generate a unique slug, appending a number if necessary.
Class Method Details
.generate(name) ⇒ String
Generate a URL-safe slug from any name.
31 32 33 34 35 36 37 38 39 40 41 42 43 |
# File 'lib/openphar/core/slug_generator.rb', line 31 def generate(name) return DEFAULT_SLUG unless name result = name.to_s.downcase .gsub(/[^a-z0-9\s-]/, '') .strip .gsub(/\s+/, '-') .gsub(/-+/, '-') .sub(/^-/, '') .sub(/-$/, '') result.empty? ? DEFAULT_SLUG : result end |
.generate_from_title(title) ⇒ String
Generate a slug from a title with potential English and Latin parts.
Titles often come in formats like:
- "Abacavir sulfate (Abacaviri sulfas)"
- "Ginger Rhizome"
78 79 80 81 82 83 84 85 |
# File 'lib/openphar/core/slug_generator.rb', line 78 def generate_from_title(title) return DEFAULT_SLUG unless title # Extract English name (before parentheses if present) english_part = title.to_s.split(/\s*\(/).first.strip generate(english_part) end |
.generate_latin(latin_name) ⇒ String
Generate a slug optimized for Latin pharmaceutical names.
Latin names often have specific formatting like:
- "Zingiberis Rhizoma" (binomial form)
- "Acacia (Gum Arabic)" (with common name)
53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 |
# File 'lib/openphar/core/slug_generator.rb', line 53 def generate_latin(latin_name) return DEFAULT_SLUG unless latin_name # Remove content in parentheses (common names) cleaned = latin_name.to_s.gsub(/\s*\([^)]*\)\s*/, ' ').strip result = cleaned.downcase .gsub(/[^a-z0-9\s-]/, '') .strip .gsub(/\s+/, '-') .gsub(/-+/, '-') .sub(/^-/, '') .sub(/-$/, '') result.empty? ? DEFAULT_SLUG : result end |
.generate_unique(name, existing_slugs) ⇒ String
Generate a unique slug, appending a number if necessary.
92 93 94 95 96 97 98 99 100 101 102 103 |
# File 'lib/openphar/core/slug_generator.rb', line 92 def generate_unique(name, existing_slugs) base_slug = generate(name) return base_slug unless existing_slugs.include?(base_slug) counter = 1 loop do candidate = "#{base_slug}-#{counter}" return candidate unless existing_slugs.include?(candidate) counter += 1 end end |