Overview
Ruby provides embedded documentation through =begin
and =end
directives that create multi-line comment blocks. These blocks serve as documentation sections within Ruby source code, allowing developers to include detailed explanations, usage examples, and metadata directly in their files.
The =begin
directive must appear at the beginning of a line, followed by optional parameters. The block continues until Ruby encounters a corresponding =end
directive, also at the beginning of a line. The Ruby interpreter ignores all content between these markers during normal execution.
=begin
This is embedded documentation.
It can span multiple lines and include
any text content.
=end
puts "This code executes normally"
Embedded documentation blocks differ from single-line comments (#
) by supporting structured content and integration with documentation tools. Tools like RDoc can extract and process these blocks to generate API documentation.
=begin rdoc
This block will be processed by RDoc
for documentation generation.
=end
class Calculator
# Regular comment
def add(a, b)
a + b
end
end
Basic Usage
The simplest embedded documentation consists of =begin
and =end
markers with content between them. The opening marker must start at column zero with no preceding whitespace.
=begin
Basic documentation block
Multiple lines supported
No special formatting required
=end
def method_name
# implementation
end
Embedded documentation supports optional type specifiers after the =begin
directive. These specifiers help documentation tools understand how to process the content.
=begin rdoc
RDoc-specific documentation
Supports RDoc markup and directives
=end
=begin pod
Plain Old Documentation format
Used by some Ruby documentation tools
=end
The content within embedded documentation blocks preserves formatting, including indentation and line breaks. This makes it suitable for detailed explanations and code examples.
=begin
Method: calculate_total
Parameters:
items - Array of item hashes
tax_rate - Float representing tax percentage
Returns:
Float - Total cost including tax
Example:
items = [{price: 10.00}, {price: 15.50}]
total = calculate_total(items, 0.08)
# => 27.54
=end
def calculate_total(items, tax_rate)
subtotal = items.sum { |item| item[:price] }
subtotal * (1 + tax_rate)
end
Advanced Usage
Embedded documentation blocks support conditional processing based on type specifiers. Documentation tools can selectively process blocks based on their declared type, enabling different documentation formats in the same file.
=begin rdoc
:main: MyClass
This class demonstrates advanced embedded documentation
techniques including cross-references and structured content.
See also: MyOtherClass, #special_method
=end
=begin yard
@author John Developer
@version 1.2.0
@since 1.0.0
=end
class MyClass
=begin rdoc
:method: initialize
:call-seq:
new(name, options = {}) -> MyClass
new(name, **kwargs) -> MyClass
Creates a new instance with the specified name and options.
Parameters:
name - String identifier for this instance
options - Hash of configuration options
Options:
:debug - Boolean enabling debug output (default: false)
:timeout - Integer timeout in seconds (default: 30)
=end
def initialize(name, **options)
@name = name
@options = {debug: false, timeout: 30}.merge(options)
end
end
Complex documentation can include metadata, cross-references, and structured content that documentation generators parse into rich output formats.
=begin rdoc
= Database Connection Manager
This module provides database connection pooling and
transaction management for Ruby applications.
== Configuration
Connection parameters:
- host: Database server hostname
- port: Database server port (default: 5432)
- database: Database name
- username: Database username
- password: Database password
== Usage Examples
# Basic connection
db = ConnectionManager.new(
host: 'localhost',
database: 'myapp_production'
)
# With connection pooling
db.with_connection do |conn|
conn.exec('SELECT * FROM users')
end
== Thread Safety
This class is thread-safe and supports concurrent access
from multiple threads. Connection pooling ensures proper
resource management in multi-threaded environments.
=end
module ConnectionManager
# Implementation details...
end
Error Handling & Debugging
Embedded documentation blocks can contain syntax that causes parsing errors when not properly formatted. The most common issue occurs when =begin
or =end
directives don't appear at the beginning of a line.
# This will cause a syntax error
=begin
Indented =begin directive fails
=end
# This will also fail
puts "code"; =begin
Documentation after code on same line
=end
# Correct usage
=begin
Properly positioned directives
=end
Mismatched =begin
and =end
blocks create syntax errors that prevent Ruby from parsing the file. Ruby reports these errors with line numbers to help locate the problem.
=begin
Missing =end directive causes syntax error
# File will not parse
=begin
First block
=end
=begin
Second block
# Missing =end for this block
def some_method
# This method will never be reached
end
Documentation tools may silently ignore malformed embedded documentation, leading to missing content in generated documentation. Validation tools can check for common formatting issues.
=begin rdoc
Properly formatted RDoc content
with correct directives and markup
=end
=begin invalidtype
Unknown type specifier may be ignored
by documentation processing tools
=end
# Use consistent type specifiers for reliable processing
=begin rdoc
Standard RDoc format ensures compatibility
with most Ruby documentation tools
=end
Production Patterns
Large codebases benefit from standardized embedded documentation patterns that ensure consistency across modules and maintain documentation quality over time.
=begin rdoc
= UserAuthentication
Handles user authentication and session management
for the application.
Author:: Security Team <security@company.com>
Version:: 2.1.0
License:: MIT
Since:: 1.0.0
== Overview
This module provides secure authentication mechanisms
including password hashing, session management, and
two-factor authentication support.
== Security Considerations
* Passwords are hashed using bcrypt with salt rounds = 12
* Sessions expire after 24 hours of inactivity
* Failed login attempts are rate-limited per IP address
* Two-factor authentication uses TOTP standard (RFC 6238)
== API Stability
This is a stable API. Breaking changes will be announced
in advance and accompanied by migration documentation.
=end
module UserAuthentication
extend self
=begin rdoc
Authenticates a user with email and password.
Returns authentication result with user object
or error details for failed attempts.
Parameters:
email - String user email address
password - String plain text password
Returns:
Hash with :success boolean and :user or :error
Security:
Implements constant-time comparison to prevent
timing attacks during password verification.
=end
def authenticate(email, password)
# Implementation with security measures
end
end
Documentation extraction workflows in production environments use automated tools to generate and deploy documentation from embedded blocks.
=begin rdoc
= API Documentation Generation
This script extracts embedded documentation from Ruby
source files and generates HTML documentation for
deployment to internal documentation servers.
== Build Process
1. Scan source directories for .rb files
2. Extract =begin rdoc blocks using RDoc parser
3. Generate HTML with custom templates
4. Deploy to documentation server with versioning
== Configuration
Set these environment variables:
- DOC_SOURCE_DIR: Root directory for source scanning
- DOC_OUTPUT_DIR: Target directory for generated docs
- DOC_VERSION: Version string for generated documentation
=end
require 'rdoc'
require 'rdoc/rdoc'
class DocumentationBuilder
=begin rdoc
Builds documentation from source files in specified directory.
Integrates with CI/CD pipelines for automated documentation
updates on code changes.
=end
def self.build_from_directory(source_dir, output_dir)
# Documentation generation implementation
end
end
Common Pitfalls
Developers often place embedded documentation in locations where it interferes with code execution or fails to integrate properly with documentation tools.
# Pitfall: Documentation inside method bodies
def process_data(input)
=begin
This documentation placement prevents proper
extraction by documentation tools and may
cause unexpected behavior.
=end
input.map(&:to_s)
end
# Correct: Documentation before method definition
=begin rdoc
Processes input data by converting elements to strings.
Parameters:
input - Enumerable collection of objects
Returns:
Array of string representations
=end
def process_data(input)
input.map(&:to_s)
end
Inconsistent type specifiers across a codebase lead to fragmented documentation generation and make it difficult to maintain comprehensive API documentation.
# Pitfall: Mixed type specifiers
=begin rdoc
Some documentation using RDoc format
=end
=begin yard
Other documentation using YARD format
=end
=begin
Plain documentation without type specifier
=end
# Correct: Consistent approach throughout codebase
=begin rdoc
All documentation uses RDoc format for consistency
and reliable tool integration
=end
Large embedded documentation blocks can make source code difficult to navigate and maintain. Long documentation should reference external files or use structured formatting.
# Pitfall: Excessive inline documentation
=begin rdoc
This is an extremely long documentation block that includes
detailed explanations, multiple examples, configuration
options, troubleshooting guides, performance considerations,
security notes, and historical information that makes the
source file difficult to read and navigate efficiently.
[... hundreds of lines of documentation ...]
This much content should be in external documentation files
with brief summaries in embedded blocks.
=end
class ComplexClass
# Implementation lost in documentation
end
# Correct: Concise embedded documentation with references
=begin rdoc
Handles complex business logic operations.
See doc/complex_class.md for detailed usage examples
and configuration options.
=end
class ComplexClass
# Clear, readable implementation
end
Reference
Directive Syntax
Directive | Position | Purpose | Example |
---|---|---|---|
=begin |
Column 0 | Start documentation block | =begin rdoc |
=end |
Column 0 | End documentation block | =end |
Type Specifiers
Type | Tool | Description |
---|---|---|
rdoc |
RDoc | Standard Ruby documentation format |
yard |
YARD | Advanced Ruby documentation with annotations |
pod |
Custom | Plain Old Documentation format |
(none) | Generic | Plain text, tool-agnostic format |
RDoc Markup Elements
Markup | Syntax | Output |
---|---|---|
Headers | = Title , == Section |
Hierarchical headings |
Bold | *bold text* |
bold text |
Italic | _italic text_ |
italic text |
Code | +code+ |
code |
Lists | * item , 1. item |
Bulleted/numbered lists |
Links | link:url |
Clickable links |
Common Documentation Patterns
Pattern | Use Case | Structure |
---|---|---|
Class Overview | Public API classes | Description, examples, notes |
Method Documentation | Public methods | Parameters, returns, examples |
Module Introduction | Namespace modules | Purpose, usage, submodules |
Configuration Guide | Configurable components | Options, defaults, examples |
Error Types
Error | Cause | Solution |
---|---|---|
Syntax Error | Indented directives | Place =begin /=end at column 0 |
Syntax Error | Unmatched blocks | Ensure every =begin has =end |
Missing Documentation | Wrong type specifier | Use tool-compatible specifiers |
Parsing Failures | Invalid markup | Follow tool-specific syntax rules |
Integration Tools
Tool | Purpose | Command | Output |
---|---|---|---|
RDoc | Generate HTML docs | rdoc lib/ |
HTML files |
YARD | Advanced documentation | yard doc |
HTML with search |
ri | Console documentation | ri ClassName |
Terminal output |
Custom | Project-specific | Varies | Custom formats |