Documentation

Comprehensive guides and references!

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

  1. Overview
  2. Quick Start
  3. Configuration Guide
  4. Implementation Examples
  5. Customization
  6. Testing
  7. 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.

  1. Use Gray Color Scheme - Ensures visual consistency
  2. Humanize Field Values - Converts snake_case to "Human readable"
  3. Maintain Accessibility - Preserves ARIA labels and semantic structure
  4. 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 ProjectBadgeComponent to 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.

Last updated: April 13, 2026

Was this helpful?

On this page