Module: Markawesome::CodeBlockProtector

Defined in:
lib/markawesome/code_block_protector.rb

Overview

Replaces fenced code blocks with opaque placeholders so that Markawesome’s component regexes (‘:::`, `^^^`, `@@@`, etc.) cannot match syntax that appears inside example code. Callers are responsible for restoring the blocks after their transformations run.

Usage:

content, tokens = Markawesome::CodeBlockProtector.protect(content)
content = some_transformer.transform(content)
content = Markawesome::CodeBlockProtector.restore(content, tokens)

The helper is stateless: each call allocates its own token map, so it is safe to use concurrently or nested. The token format is a stable HTML comment so that it survives markdown conversion intact.

Constant Summary collapse

CODE_BLOCK_PATTERN =
/```([a-zA-Z0-9.+#_-]+)?(\n.*?)```/m
PLACEHOLDER_PREFIX =
'<!--MARKAWESOME_PROTECTED_CODE_BLOCK_'
PLACEHOLDER_SUFFIX =
'-->'

Class Method Summary collapse

Class Method Details

.protect(content) ⇒ Array(String, Hash)

Replace every fenced code block with a placeholder.

Parameters:

  • content (String)

Returns:

  • (Array(String, Hash))

    Protected content and placeholder→block map.



27
28
29
30
31
32
33
34
35
36
37
38
39
# File 'lib/markawesome/code_block_protector.rb', line 27

def protect(content)
  tokens = {}
  counter = 0

  protected_content = content.gsub(CODE_BLOCK_PATTERN) do |match|
    placeholder = "#{PLACEHOLDER_PREFIX}#{counter}#{PLACEHOLDER_SUFFIX}"
    tokens[placeholder] = match
    counter += 1
    placeholder
  end

  [protected_content, tokens]
end

.restore(content, tokens) ⇒ String

Restore placeholders created by protect.

Parameters:

  • content (String)
  • tokens (Hash)

Returns:

  • (String)


45
46
47
48
49
50
51
52
# File 'lib/markawesome/code_block_protector.rb', line 45

def restore(content, tokens)
  return content if tokens.nil? || tokens.empty?

  tokens.each do |placeholder, original|
    content = content.gsub(placeholder, original)
  end
  content
end