Generators Overview
Generators Overview
Azu CLI's generator system is one of its most powerful features, allowing you to rapidly scaffold components, models, services, and complete applications. This guide provides an overview of how generators work, the philosophy behind them, and how to use them effectively.
What Are Generators?
Generators are automated code creation tools that follow Azu's conventions and best practices. They create files, directories, and boilerplate code based on templates, saving you time and ensuring consistency across your application.
Generator Philosophy
Convention Over Configuration
Generators follow established patterns and naming conventions, so you don't have to make decisions about file organization, naming, or structure.
DRY (Don't Repeat Yourself)
Instead of writing boilerplate code repeatedly, generators create it for you with proper patterns and best practices built-in.
Test-Driven Development
All generators create corresponding test files, encouraging you to write tests alongside your application code.
Modular Architecture
Each generator creates focused, single-responsibility components that work together as part of a larger system.
Available Generators
Generator Types
1. Structural Generators
Create the main building blocks of your application:
Model: Data layer with database persistence
Endpoint: HTTP request handling and routing
Service: Business logic encapsulation
Middleware: Request/response processing
2. Interface Generators
Create user-facing components:
Page: HTML rendering and templates
Component: Interactive, real-time UI elements
Contract: API input/output contracts
3. Utility Generators
Create supporting functionality:
Validator: Custom validation logic
Migration: Database schema management
4. Composite Generators
Create multiple related files:
Scaffold: Complete CRUD resource with all components
Generator Workflow
1. Planning Phase
Before running a generator, consider:
Component name (should be descriptive and follow conventions)
Attributes (for models, contracts, components)
Relationships (how it connects to other components)
Custom options (API-only, skip tests, etc.)
2. Generation Phase
3. Customization Phase
After generation:
Review generated files for accuracy
Customize business logic in services and endpoints
Add validations to models and contracts
Write tests for your specific use cases
Update routes if needed
4. Integration Phase
Connect components together
Update imports and dependencies
Run migrations for database changes
Test the complete feature
Common Generator Patterns
1. Resource-Based Generation
For typical CRUD resources:
2. Service-Oriented Generation
For complex business logic:
3. API-First Generation
For API-only applications:
4. Component-Based Generation
For interactive features:
Generator Options
Global Options
Available for all generators:
--force
Overwrite existing files
false
--skip-tests
Don't generate test files
false
--help
Show generator help
Specific Options
Different generators have specialized options:
Endpoint Generator:
--api- Generate API-only (no pages/templates)--actions <list>- Specify which CRUD actions
Model Generator:
--validations- Add common validations--timestamps- Add created_at/updated_at--uuid- Use UUID primary key
Component Generator:
--websocket- Enable real-time features--events <list>- Custom event handlers
Naming Conventions
Component Names
PascalCase for class names:
User,BlogPost,UserRegistrationsnake_case for file names:
user.cr,blog_post.cr,user_registration.crPluralized for collections:
users(endpoints),posts(tables)
File Organization
Namespace Conventions
Endpoints:
Users::IndexEndpointContracts:
Users::CreateContractPages:
Users::IndexPageModels:
User(no namespace)Services:
UserRegistrationServiceComponents:
CounterComponent
Template System
How Templates Work
Generators use ECR (Embedded Crystal) templates:
Template Variables
Common variables available in templates:
class_name
PascalCase class name
User
file_name
snake_case file name
user
table_name
Database table name
users
namespace
Module namespace
Users
attributes
Hash of attributes
{"name" => "string"}
project_name
Current project name
my_blog
Custom Templates
You can override default templates:
Create template directory:
Create custom template:
Use custom template:
Generated File Structure
Complete Example
When you run azu generate scaffold Post title:string content:text, you get:
Best Practices
1. Planning Before Generation
Design your models first to understand relationships
Plan your API structure before generating endpoints
Consider reusable components for common functionality
2. Consistent Naming
Use descriptive names that clearly indicate purpose
Follow Crystal conventions for naming
Be consistent across your application
3. Incremental Generation
Start with models to establish your data layer
Add services for business logic
Generate endpoints for HTTP interface
Use scaffold only for rapid prototyping
4. Customization After Generation
Review all generated code before committing
Add custom validation rules to models
Implement business logic in services
Customize templates to match your UI needs
5. Testing Strategy
Don't skip test generation unless absolutely necessary
Customize generated tests for your specific requirements
Add integration tests for complete workflows
Test both success and failure scenarios
Advanced Usage
1. Batch Generation
2. Template Customization
3. Generator Configuration
Troubleshooting
Common Issues
File Already Exists
Invalid Attribute Format
Missing Dependencies
Generator Not Found
Getting Help
The generator system is designed to accelerate your development while maintaining code quality and consistency. Master these tools to become highly productive with Azu applications.
Next Steps:
Endpoint Generator - Generate HTTP request handlers
Model Generator - Create database models
Development Workflows - Use generators in real projects
README Generator
The README Generator creates comprehensive, well-structured README.md files following modern documentation best practices for Crystal projects.
Overview
The README generator produces professional README.md files that include:
Project metadata: title, description, badges, license information
Installation instructions: both shards and manual installation
Usage examples: tailored to project type (library, CLI, web, service)
Development setup: prerequisites, setup steps, testing, building
Contribution guidelines: standards, workflow, issue reporting
Comprehensive sections: API docs, changelog, roadmap, support
Usage
Basic Usage
Generate a basic README.md file:
This creates a README.md file in the current directory with:
Project title: "My Project" (formatted)
Default description: "A Crystal project"
Standard sections for a library project
MIT license and basic author info
Default features and badges
Advanced Usage
Generate with custom configuration:
Project Type Specific Generation
Generate README tailored to specific project types:
Programmatic Usage
Generated Output
Example README.md
Generated for a web application with PostgreSQL:
Web Application
Start the server:
Open your browser and visit:
Configuration
Create a .env file in the project root:
Development
Prerequisites
Crystal >= 1.16.0
PostgreSQL database
Setup
Clone your fork...
Install dependencies...
Set up the database...
Contributing
Fork it
Create your feature branch
Make your changes and add tests
Ensure all tests pass
Format your code
Run the linter
Commit your changes
Push to the branch
Create a new Pull Request
License
This project is licensed under the MIT License - see the LICENSE file for details.
Database Integration
When database support is specified, the README includes:
PostgreSQL
Database setup instructions
Connection configuration
Migration commands
Prerequisites section mentions PostgreSQL
MySQL
MySQL-specific setup
Connection string examples
Database creation steps
SQLite
File-based database info
Simplified setup process
Local development focus
None
Omits database-related sections
Focuses on application logic
Simplified prerequisites
Advanced Features
Badges and Shields
Automatically includes relevant badges:
CI/CD Status: GitHub Actions workflow status
Release Version: Latest GitHub release version
License: License type with appropriate color
Custom badges: Can be extended for specific needs
Author Attribution
Generates GitHub links for authors:
Extracts names from email format:
"John Doe <john@example.com>"Creates GitHub profile links:
https://github.com/john-doeAssigns roles: first author is "creator and maintainer", others are "contributors"
Roadmap Integration
When enabled, includes:
Checkbox-style roadmap items
Future feature planning
Development priorities
Community engagement
Support Information
Customizable support section:
Default: generic contribution encouragement
Custom: specific support channels, contact info
Community resources and links
Validation
The generator validates:
Project names: Must be valid Crystal identifiers
GitHub usernames: Must follow GitHub username format
Required fields: Description, license, crystal version cannot be empty
Author format: Authors array cannot be empty
Features: Feature descriptions cannot be empty
Integration with Azu CLI
The README generator integrates with the main azu generate command:
Best Practices
Content Guidelines
Write clear, concise descriptions
Include comprehensive installation instructions
Provide working code examples
Document all configuration options
Keep README updated with project changes
Project Type Selection
Library: Choose for reusable packages and modules
CLI: Choose for command-line tools and utilities
Web: Choose for web applications and websites
Service: Choose for APIs and microservices
GitHub Integration
Use your actual GitHub username
Ensure repository names match project names
Set up CI/CD workflows referenced in badges
Create LICENSE file to match specified license
Feature Description
Use emoji for visual appeal and scanning
Focus on user benefits, not technical details
Keep descriptions short and impactful
Highlight unique selling points
Database Documentation
Document all required environment variables
Provide working connection examples
Include database schema information
Document migration and seeding processes
Troubleshooting
Common Issues
Invalid GitHub username error:
Solution: Use valid GitHub username format (alphanumeric, hyphens allowed, cannot start/end with hyphen)
Empty description error:
Solution: Provide a meaningful project description
Unsupported project type:
Solution: Use one of the supported types: library, cli, web, service
Debugging
Check generated content:
Validate Markdown syntax:
Preview rendered output:
Examples
Minimal Library
Full-Featured Web App
CLI Tool
Related Documentation
Last updated