Ruby Formatters: RuboCop & ERB-Formatter Docs | Web Formatter Blog

Ruby Formatters: RuboCop & ERB-Formatter Docs
A comprehensive guide to Ruby code formatting tools: RuboCop for Ruby files and ERB-Formatter for ERB templates.
Introduction to Ruby Formatters
Code formatting is a crucial aspect of maintaining clean, readable, and consistent Ruby codebases. In the Ruby ecosystem, two tools stand out for their effectiveness and widespread adoption: RuboCop for Ruby files and ERB-Formatter for ERB templates commonly used in Ruby on Rails applications.
This comprehensive guide provides detailed documentation for both tools, covering installation, configuration, usage patterns, and integration with development workflows. Whether you're a Ruby beginner or an experienced developer, this reference will help you maintain code quality and consistency across your projects.
RuboCop
RuboCop is more than just a formatter—it's a robust static code analyzer and formatter for Ruby. It enforces many of the guidelines outlined in the community-driven Ruby Style Guide.
Installation
RuboCop can be installed as a gem. Add it to your Gemfile or install it directly:
# Add to your Gemfile
gem 'rubocop', require: false
# Or install directly
gem install rubocop
For Rails projects, consider using the rubocop-rails extension:
# Add to your Gemfile
gem 'rubocop-rails', require: false
Basic Usage
Once installed, you can run RuboCop from the command line:
# Check all Ruby files in the current directory
rubocop
# Check specific files or directories
rubocop app lib/my_file.rb
# Format output as JSON
rubocop --format json
# Display cop names
rubocop --display-cop-names
Configuration
RuboCop is highly configurable through a .rubocop.yml
file placed in your project's root directory:
# .rubocop.yml
AllCops:
TargetRubyVersion: 3.1
NewCops: enable
Exclude:
- 'db/**/*'
- 'config/**/*'
- 'bin/**/*'
- 'vendor/**/*'
# Style configurations
Style/StringLiterals:
EnforcedStyle: single_quotes
Style/Documentation:
Enabled: false
# Layout configurations
Layout/LineLength:
Max: 100
# Metrics configurations
Metrics/MethodLength:
Max: 15
Metrics/BlockLength:
Exclude:
- 'spec/**/*'
You can inherit from other configuration files:
inherit_from:
- .rubocop_todo.yml
- .rubocop_company_defaults.yml
Or inherit from gems:
inherit_gem:
rubocop-rails_config: config/rails.yml
Understanding Cops
RuboCop organizes its rules into "cops," each responsible for detecting specific offenses:
- Layout: Spacing, alignment, and formatting
- Lint: Potential bugs and suspicious constructs
- Metrics: Code complexity measurements
- Naming: Naming conventions
- Security: Security vulnerabilities
- Style: Stylistic choices and best practices
You can enable or disable specific cops:
# Enable specific cops
Style/StringLiterals:
Enabled: true
# Disable specific cops
Style/FrozenStringLiteralComment:
Enabled: false
Auto-correction
One of RuboCop's most powerful features is its ability to automatically fix many issues:
# Safe auto-corrections
rubocop -a
# Safe and unsafe auto-corrections
rubocop -A
The difference between -a
(or --auto-correct
) and -A
(or --auto-correct-all
) is that the latter will make corrections that might change the behavior of your code.
Extensions
RuboCop's functionality can be extended with specialized gems:
- rubocop-rails: Rails-specific rules
- rubocop-rspec: RSpec-specific rules
- rubocop-performance: Performance optimization rules
- rubocop-minitest: Minitest-specific rules
- rubocop-rake: Rake-specific rules
To use extensions, add them to your Gemfile and configure them in .rubocop.yml
:
require:
- rubocop-rails
- rubocop-rspec
- rubocop-performance
IDE Integration
RuboCop integrates with most popular IDEs and text editors:
- VS Code: Use the "Ruby" extension
- RubyMine: Built-in support
- Sublime Text: SublimeLinter-rubocop
- Vim: ALE or Syntastic
- Emacs: Flycheck
ERB-Formatter
ERB-Formatter (erb-formatter) is a specialized tool for formatting ERB templates, commonly used in Ruby on Rails views.
Installation
ERB-Formatter can be installed as a gem:
# Add to your Gemfile
gem 'erb-formatter', require: false
# Or install directly
gem install erb-formatter
Basic Usage
Once installed, you can run ERB-Formatter from the command line:
# Format a single file
erb-formatter app/views/users/index.html.erb
# Format multiple files
erb-formatter app/views/**/*.erb
# Check if files are formatted without changing them
erb-formatter --check app/views/**/*.erb
# Write changes to files
erb-formatter --write app/views/**/*.erb
Configuration
ERB-Formatter can be configured through a .erb-formatter.yml
file in your project's root directory:
# .erb-formatter.yml
indent: 2
tab_width: 2
max_line_length: 100
print_width: 100
ruby_parser: ripper # or 'syntax_tree'
Key configuration options include:
- indent: Number of spaces for indentation
- tab_width: Width of tab characters
- max_line_length: Maximum line length before wrapping
- print_width: Target line length for formatting
- ruby_parser: Parser to use for Ruby code (ripper or syntax_tree)
Comparison with Alternatives
ERB-Formatter is not the only tool for formatting ERB templates. Here's how it compares to alternatives:
Feature | ERB-Formatter | HTML-ERB-Lint | Prettier (with plugin) |
---|---|---|---|
Ruby-aware formatting | ✅ | ✅ | ⚠️ Limited |
HTML formatting | ✅ | ✅ | ✅ |
Configuration options | Medium | High | High |
Integration with Ruby tools | ✅ | ✅ | ⚠️ Limited |
Active maintenance | ✅ | ⚠️ Moderate | ✅ |
IDE Integration
ERB-Formatter can be integrated with popular IDEs:
- VS Code: Use the "ERB Formatter" extension
- RubyMine: Configure as an external tool
- Vim: Configure with ALE
- Sublime Text: Set up as a build system
For VS Code, you can configure the extension to format on save:
// settings.json
{
"[erb]": {
"editor.defaultFormatter": "aliariff.vscode-erb-formatter",
"editor.formatOnSave": true
}
}
Best Practices
To get the most out of RuboCop and ERB-Formatter, follow these best practices:
- Start with defaults: Begin with the default configurations and customize gradually
- Use a .rubocop_todo.yml: For legacy projects, generate a todo file to gradually address issues:
rubocop --auto-gen-config
- Format on save: Configure your IDE to format files automatically when saving
- Include in code reviews: Make passing RuboCop checks a requirement for code review approval
- Customize thoughtfully: Only override default rules when you have a good reason
- Document exceptions: When disabling a cop inline, always include a comment explaining why:
# rubocop:disable Style/StringLiterals some_method("with double quotes for a good reason") # rubocop:enable Style/StringLiterals
- Update regularly: Keep your RuboCop and ERB-Formatter gems updated to benefit from improvements
CI/CD Integration
Integrating RuboCop and ERB-Formatter into your CI/CD pipeline ensures consistent code quality:
GitHub Actions Example:
# .github/workflows/linters.yml
name: Linters
on: [push, pull_request]
jobs:
rubocop:
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v3
- uses: ruby/setup-ruby@v1
with:
ruby-version: '3.1'
bundler-cache: true
- name: Run RuboCop
run: bundle exec rubocop
erb-formatter:
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v3
- uses: ruby/setup-ruby@v1
with:
ruby-version: '3.1'
bundler-cache: true
- name: Run ERB-Formatter
run: bundle exec erb-formatter --check app/views/**/*.erb
GitLab CI Example:
# .gitlab-ci.yml
rubocop:
stage: lint
image: ruby:3.1
script:
- gem install rubocop
- rubocop
erb-formatter:
stage: lint
image: ruby:3.1
script:
- gem install erb-formatter
- erb-formatter --check app/views/**/*.erb
Troubleshooting Common Issues
Here are solutions to common issues you might encounter:
RuboCop is too slow
- Use
--parallel
to run checks in parallel - Use
--only
to run specific cops - Exclude large directories in your configuration
- Use
rubocop --cache
to enable caching
Too many offenses in legacy code
- Generate a todo file:
rubocop --auto-gen-config
- Address offenses incrementally
- Use
--only
to focus on specific categories
ERB-Formatter breaks ERB syntax
- Check for unclosed ERB tags in your templates
- Try using a different Ruby parser in the configuration
- Format smaller chunks of code to isolate the issue
Conflicts between RuboCop and other tools
- Ensure consistent configuration across tools
- Consider using Prettier with appropriate plugins for frontend code
- Document your team's approach to resolving conflicts
Conclusion
RuboCop and ERB-Formatter are powerful tools that help maintain code quality and consistency in Ruby and Rails projects. By incorporating these tools into your development workflow, you can:
- Enforce consistent coding styles across your team
- Catch potential bugs and code smells early
- Improve code readability and maintainability
- Reduce time spent on formatting discussions in code reviews
- Gradually improve legacy codebases
Remember that these tools are meant to serve your team, not the other way around. Don't hesitate to customize configurations to match your project's specific needs, but do so thoughtfully and with team consensus.
By following the guidelines in this documentation, you'll be well-equipped to leverage RuboCop and ERB-Formatter effectively in your Ruby and Rails projects.