Class: Mdtoc::Markdown::FragmentGenerator::GitHub
- Inherits:
-
Object
- Object
- Mdtoc::Markdown::FragmentGenerator::GitHub
- Extended by:
- T::Sig
- Includes:
- Mdtoc::Markdown::FragmentGenerator
- Defined in:
- lib/mdtoc/markdown/fragment_generator.rb
Instance Method Summary collapse
- #generate(label) ⇒ Object
-
#initialize ⇒ GitHub
constructor
A new instance of GitHub.
Constructor Details
#initialize ⇒ GitHub
Returns a new instance of GitHub.
22 23 24 |
# File 'lib/mdtoc/markdown/fragment_generator.rb', line 22 def initialize @counts = T.let(Hash.new(0), T::Hash[String, Integer]) end |
Instance Method Details
#generate(label) ⇒ Object
27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 |
# File 'lib/mdtoc/markdown/fragment_generator.rb', line 27 def generate(label) # GitHub's fragment generation: # 1. Downcase # 2. Replace spaces with dashes # 3. Remove non-alphanumeric characters (keeping dashes, dots and underscores) # 4. Collapse multiple dashes # 5. Remove leading/trailing dashes and dots (common in many implementations) fragment = label.downcase.tr(' ', '-').gsub(/[^\w.-]/, '') fragment = fragment.gsub(/-+/, '-') fragment = fragment.gsub(/^[.-]+|[.-]+$/, '') count = @counts[fragment] @counts[fragment] += 1 if count.positive? "#{fragment}-#{count}" else fragment end end |