Class: Autodoc::Examples

Inherits:
Object
  • Object
show all
Defined in:
lib/ratatui_ruby/devtools/tasks/autodoc/examples.rb

Overview

Synchronizes code snippets from source files into markdown.

Markdown files contain embedded code examples. Maintaining them manually drifts from the source. This class scans for SYNC markers and injects live code from the referenced files.

Use it to sync README.md examples with your actual implementation.

Example

In your README.md:

<!-- SYNC:START:examples/hello/app.rb:main -->
```ruby
# This content gets replaced
```
<!-- SYNC:END -->

Then run:

Autodoc::Examples.sync

Class Method Summary collapse

Instance Method Summary collapse

Class Method Details

.syncObject

Synchronize all README files in the repository.



40
41
42
# File 'lib/ratatui_ruby/devtools/tasks/autodoc/examples.rb', line 40

def self.sync
  new.sync
end

Instance Method Details

#extract_segment(content, segment_id, source_path) ⇒ Object

Extracts a named segment from source content.

Source files contain segment markers like [SYNC:START:main]. This method extracts the content between matching markers.

content

The source file content.

segment_id

The segment name to extract.

source_path

The source file path (for error messages).



103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
# File 'lib/ratatui_ruby/devtools/tasks/autodoc/examples.rb', line 103

def extract_segment(content, segment_id, source_path)
  start_marker = /#\s*\[SYNC:START:#{segment_id}\]/
  end_marker = /#\s*\[SYNC:END:#{segment_id}\]/

  lines = content.lines
  start_idx = lines.find_index { |l| l =~ start_marker }
  end_idx = lines.find_index { |l| l =~ end_marker }

  if start_idx && end_idx
    "#{unindent(lines[(start_idx + 1)...end_idx].join).strip}\n"
  else
    warn "Warning: Segment '#{segment_id}' not found in #{source_path}"
    content
  end
end

#syncObject

Synchronize all README files.

Scans for SYNC markers in markdown files and replaces content with source file snippets.



48
49
50
51
52
# File 'lib/ratatui_ruby/devtools/tasks/autodoc/examples.rb', line 48

def sync
  Dir.glob("{README.md,doc/**/*.md,examples/*/README.md}").each do |readme_path|
    sync_readme(readme_path)
  end
end

#unindent(text) ⇒ Object

Removes common leading indentation from text.

Code segments often have indentation from their context. This method strips the common prefix so the output looks clean.

text

The text to unindent.



125
126
127
128
129
130
131
# File 'lib/ratatui_ruby/devtools/tasks/autodoc/examples.rb', line 125

def unindent(text)
  lines = text.lines
  return text if lines.empty?

  indentation = lines.grep(/\S/).map { |l| l[/^\s*/].length }.min || 0
  lines.map { |l| (l.length > indentation) ? l[indentation..-1] : "#{l.strip}\n" }.join
end