Universal Badge System Documentation
A flexible, reusable badge system for Rails applications providing consistent status indicators across any model using traditional partials and helpers.
Table of Contents
- Overview
- Quick Start
- Configuration Guide
- Implementation Examples
- Customization
- Testing
- Migration Guide
Overview
๐ฏ Key Features
The Universal Badge System transforms status indicators into beautifully styled, accessible components that work across your entire Rails application.
Core Capabilities
| Feature | Description | Benefit |
|---|---|---|
| Universal Compatibility | Works with any ActiveRecord model | Consistent UI across features |
| Configurable Styling | Pre-defined color schemes and sizes | Professional appearance |
| Dark Mode Support | Automatic theme adaptation | Modern UX standards |
| Accessibility First | ARIA labels and semantic markup | WCAG 2.2 AA compliance |
| Easy Extension | Simple configuration for new models | Rapid development |
Supported Configurations
โ Ready-to-Use Badge Types
Pre-configured badge types that work immediately with your existing models.
- โ Project Status Badges (active, planning, on_hold, completed, cancelled)
- โ Project Priority Levels (1-5 with color coding)
- โ User Role Indicators (admin, manager, member, guest)
- โ Dynamic Fallback (automatic styling for unconfigured fields)
Quick Start
Basic Usage Examples
๐ก Simple Implementation
Get started with badges in seconds using these straightforward examples.
<!-- Project status badge -->
<%= render 'shared/badge', object: project, field: :status %>
<!-- Project priority with custom size -->
<%= render 'shared/badge', object: project, field: :priority, size: :lg %>
<!-- User role badge -->
<%= render 'shared/badge', object: user, field: :role, size: :sm %>
<!-- Automatic styling for any model -->
<%= render 'shared/badge', object: task, field: :urgency %>
Available Badge Sizes
| Size | CSS Classes | Best Use Case |
|---|---|---|
:sm |
px-2 py-0.5 text-xs |
Dense layouts, tables |
:md |
px-2.5 py-0.5 text-xs |
Standard display (default) |
:lg |
px-3 py-1 text-sm |
Emphasis, hero sections |
Configuration Guide
Configuration Structure
All badge configurations are defined in app/helpers/badge_helper.rb using the BADGE_CONFIGURATIONS hash:
๐ง Configuration Pattern
Each model can have multiple badge types, with complete control over colors, labels, and display logic.
BADGE_CONFIGURATIONS = {
project: {
status: {
type: :status,
values: {
'active' => { color: 'green', label: 'Active' },
'planning' => { color: 'gray', label: 'Planning' },
'on_hold' => { color: 'yellow', label: 'On Hold' },
'completed' => { color: 'blue', label: 'Completed' },
'cancelled' => { color: 'red', label: 'Cancelled' }
}
},
priority: {
type: :priority,
values: {
1 => { color: 'gray', label: 'Low' },
2 => { color: 'blue', label: 'Medium' },
3 => { color: 'yellow', label: 'High' },
4 => { color: 'orange', label: 'Critical' },
5 => { color: 'red', label: 'Emergency' }
}
}
},
user: {
role: {
type: :role,
values: {
'admin' => { color: 'red', label: 'Admin' },
'manager' => { color: 'blue', label: 'Manager' },
'member' => { color: 'green', label: 'Member' },
'guest' => { color: 'gray', label: 'Guest' }
}
}
}
}
Color Scheme Reference
The badge system provides six carefully designed color schemes with automatic dark mode adaptation:
๐จ Professional Color Palette
Thoughtfully designed color schemes that provide excellent contrast and accessibility in both light and dark modes.
| Color | Light Theme | Dark Theme | Use Case |
|---|---|---|---|
gray |
Neutral gray | Dark gray | Default/pending states |
green |
Success green | Bright green | Success/active states |
blue |
Info blue | Bright blue | Information/processing |
yellow |
Warning amber | Golden yellow | Warnings/attention |
orange |
Alert orange | Warm orange | High priority/urgent |
red |
Error red | Bright red | Errors/critical states |
Implementation Examples
Adding New Model Support
๐ Step-by-Step Process
Follow this pattern to add badge support for any new model in your application.
1. Define Configuration
Add a new section to BADGE_CONFIGURATIONS:
๐ง Configuration Setup
Define badge types and color mappings for your new model.
BADGE_CONFIGURATIONS = {
# ... existing configurations ...
task: {
status: {
type: :status,
values: {
'todo' => { color: 'gray', label: 'To Do' },
'in_progress' => { color: 'blue', label: 'In Progress' },
'review' => { color: 'yellow', label: 'In Review' },
'done' => { color: 'green', label: 'Done' }
}
},
urgency: {
type: :urgency,
values: {
'low' => { color: 'gray', label: 'Low' },
'medium' => { color: 'yellow', label: 'Medium' },
'high' => { color: 'red', label: 'High' }
}
}
}
}
2. Implement in Views
๐จ View Integration
Add badges to your templates using the consistent render pattern.
<!-- Task status badges -->
<%= render 'shared/badge', object: task, field: :status %>
<%= render 'shared/badge', object: task, field: :urgency, size: :sm %>
<!-- In table layouts -->
<tr>
<td><%= task.title %></td>
<td><%= render 'shared/badge', object: task, field: :status %></td>
<td><%= render 'shared/badge', object: task, field: :urgency, size: :sm %></td>
</tr>
3. Test Implementation
๐งช Verification Process
Validate that your configuration is working correctly.
# Verify configuration works
rails console
> task = Task.first
> helper.badge_configured?(task, :status)
=> true
> helper.badge_text_for(task, :status)
=> "To Do"
Advanced Usage Patterns
Direct Helper Methods
๐ ๏ธ Advanced Integration
Use helper methods directly for custom implementations or conditional logic.
<!-- Get CSS classes directly -->
<span class="<%= badge_classes_for(project, :status, size: :lg) %>">
<%= badge_text_for(project, :status) %>
</span>
<!-- Conditional rendering -->
<% if badge_configured?(project, :status) %>
<%= render 'shared/badge', object: project, field: :status %>
<% else %>
<span class="text-gray-500 text-sm">
<%= project.status.humanize %>
</span>
<% end %>
Bulk Badge Display
๐ Multiple Badge Patterns
Effective patterns for displaying multiple badges and contextual information.
<!-- Display multiple badges for one object -->
<div class="flex gap-2">
<%= render 'shared/badge', object: project, field: :status %>
<%= render 'shared/badge', object: project, field: :priority, size: :sm %>
</div>
<!-- Badge with additional context -->
<div class="flex items-center gap-2">
<span class="text-sm font-medium">Priority:</span>
<%= render 'shared/badge', object: project, field: :priority %>
</div>
Customization
Fallback Behavior
๐ก๏ธ Graceful Degradation
The system automatically handles unconfigured models and fields with intelligent fallbacks.
For unconfigured models or fields, the badge system will:
โ๏ธ Automatic Handling
Smart fallback behavior ensures badges always look professional, even without explicit configuration.
- Use Gray Color Scheme - Ensures visual consistency
- Humanize Field Values - Converts
snake_caseto "Human readable" - Maintain Accessibility - Preserves ARIA labels and semantic structure
- Apply Standard Styling - Same visual appearance as configured badges
<!-- This works even without configuration -->
<%= render 'shared/badge', object: custom_model, field: :custom_status %>
<!-- Renders: "Custom status" with gray styling -->
Accessibility Features
Every badge automatically includes comprehensive accessibility support:
โฟ WCAG 2.2 AA Compliance
Built-in accessibility features ensure your badges work for all users.
| Feature | Implementation | Benefit |
|---|---|---|
| ARIA Labels | aria-label="Status: Active" |
Screen reader support |
| Title Attributes | title="Current status is Active" |
Hover tooltips |
| Data Attributes | data-type="status" data-value="active" |
JavaScript integration |
| Semantic Markup | Proper <span> elements |
Document structure |
| Focus Indicators | Visible focus states | Keyboard navigation |
Custom Styling
๐จ Advanced Customization
Extend the badge system with custom colors and styling while maintaining accessibility.
Adding Custom Colors
๐ Color Extension
Add new color schemes to match your brand or specific use cases.
# In app/helpers/badge_helper.rb, extend color mappings
private
def badge_color_classes(color)
case color
when 'custom_purple'
'bg-purple-100 text-purple-800 dark:bg-purple-900 dark:text-purple-300'
when 'custom_teal'
'bg-teal-100 text-teal-800 dark:bg-teal-900 dark:text-teal-300'
else
# ... existing color mappings
end
end
Custom Badge Sizes
๐ Size Customization
Define custom sizes for specific layout requirements.
# Extend size configurations
def badge_size_classes(size)
case size&.to_sym
when :xs
'px-1.5 py-0.5 text-xs'
when :xl
'px-4 py-1.5 text-base'
else
# ... existing size mappings
end
end
Testing
Test Coverage
The badge system includes comprehensive tests in test/helpers/badge_helper_test.rb:
โ Quality Assurance
Complete test suite ensures reliability and prevents regressions.
Test Categories
๐งช Comprehensive Testing
All aspects of badge functionality are thoroughly tested to ensure reliability.
- โ CSS Class Generation - Validates correct styling classes
- โ Text Display Logic - Ensures proper label rendering
- โ Configuration Lookup - Tests configuration resolution
- โ Size Validation - Verifies size parameter handling
- โ Color Mapping - Confirms color scheme application
- โ Fallback Behavior - Tests unconfigured model handling
Running Tests
๐ Test Execution
Commands for running the badge system test suite.
# Run badge helper tests
rails test test/helpers/badge_helper_test.rb
# Run specific test methods
rails test test/helpers/badge_helper_test.rb -n test_badge_classes_for_configured_badge
# Run with verbose output
rails test test/helpers/badge_helper_test.rb --verbose
Example Test Cases
๐ Test Structure
Sample test patterns demonstrating comprehensive badge testing.
# Sample test structure
test "badge_classes_for returns correct CSS classes" do
project = projects(:active_project)
classes = badge_classes_for(project, :status, size: :lg)
assert_includes classes, 'bg-green-100'
assert_includes classes, 'text-green-800'
assert_includes classes, 'px-3 py-1'
end
test "fallback behavior for unconfigured models" do
unconfigured_object = create(:custom_model)
text = badge_text_for(unconfigured_object, :custom_field)
assert_equal "Custom field", text
end
Migration Guide
Upgrading from ViewComponent
๐ Migration Path
Seamlessly transition from the legacy
ProjectBadgeComponentto the universal system.
Before (ViewComponent Implementation)
๐ Legacy Pattern
Old component-based approach with limited flexibility.
<%= render ProjectBadgeComponent.new(type: :status, value: project.status) %>
<%= render ProjectBadgeComponent.new(type: :priority, value: project.priority, size: :lg) %>
After (Universal Badge System)
๐ Modern Implementation
New universal approach with enhanced flexibility and performance.
<%= render 'shared/badge', object: project, field: :status %>
<%= render 'shared/badge', object: project, field: :priority, size: :lg %>
Migration Benefits
๐ Improvement Overview
Key advantages of migrating to the universal badge system.
| Aspect | Old System | New System |
|---|---|---|
| Flexibility | Project-only | Any model |
| Configuration | Component-based | Centralized |
| Maintenance | Multiple components | Single system |
| Performance | Component overhead | Lightweight partials |
| Accessibility | Manual implementation | Built-in support |
Migration Checklist
๐ Step-by-Step Migration
Complete checklist for smooth transition to the new badge system.
- Update View Files - Replace component calls with partial renders
- Configure New Models - Add badge configurations for additional models
- Test Functionality - Verify all badges render correctly
- Update Documentation - Reference new usage patterns
- Remove Old Components - Clean up deprecated ViewComponent files
๐ Migration Complete!
The universal badge system provides enhanced flexibility while maintaining the same visual appearance and improving performance.
Summary
The Universal Badge System provides:
๐ Complete Badge Solution
A comprehensive, flexible, and accessible badge system that works seamlessly across your entire Rails application.
- ๐ Universal Compatibility - Works with any ActiveRecord model
- ๐จ Beautiful Styling - Professional appearance with dark mode support
- โฟ Accessibility First - WCAG 2.2 AA compliant by default
- โก High Performance - Lightweight partial-based architecture
- ๐ง Easy Configuration - Centralized configuration management
- ๐ก๏ธ Graceful Fallbacks - Handles unconfigured models elegantly
- ๐ Comprehensive Testing - Full test coverage for reliability
๐ Pro Tip
Start with the basic configuration and gradually extend the system as you add new models. The fallback behavior ensures your badges always look professional, even for unconfigured fields.