Ruby & Rails Formatting Using RuboCop & ERB-Formatter | Web Formatter Blog

Ruby & Rails Formatting Using RuboCop & ERB-Formatter
A comprehensive guide to formatting Ruby and Rails code for improved readability and maintainability.
Introduction to Ruby Formatting
Ruby's elegant syntax is one of its most celebrated features, enabling developers to write expressive and readable code. However, with this flexibility comes the need for consistent formatting standards, especially in team environments or large projects.
In this comprehensive guide, we'll explore how to leverage RuboCop and ERB-Formatter to maintain beautiful, consistent Ruby and Rails code across your projects, ensuring both readability and adherence to community best practices.
Why Format Your Ruby Code?
The benefits of consistent formatting extend far beyond aesthetics:
- Improved readability: Consistently formatted code is easier to scan and comprehend
- Reduced cognitive load: Developers can focus on logic rather than style discrepancies
- Easier onboarding: New team members can quickly adapt to your codebase's style
- Faster code reviews: Reviewers can focus on substance rather than style
- Bug prevention: Many formatting rules catch potential issues before they become bugs
- Enforced best practices: Tools like RuboCop encode Ruby community standards
While the Ruby community has long prized the language's flexibility, a general consensus around style has emerged over time, largely documented in the{" "} Ruby Style Guide . RuboCop implements these guidelines, making it easy to follow community standards.
Understanding RuboCop
RuboCop is far more than just a code formatter—it's a static code analyzer and formatter that enforces many of the guidelines outlined in the community Ruby Style Guide. It helps identify and fix:
- Style violations: Inconsistent whitespace, quotes, string interpolation, etc.
- Code smells: Methods that are too long or complex, unused variables, etc.
- Security vulnerabilities: Unsafe use of eval, SQL injection risks, etc.
- Performance issues: Inefficient algorithms, unnecessary object allocations, etc.
- Rails-specific issues: Common Rails anti-patterns, unsafe controller actions, etc.
RuboCop organizes its rules (called "cops") into several departments: Style, Layout, Lint, Metrics, Security, Performance, and Rails. Each department focuses on a different aspect of code quality.
Meanwhile, ERB-Formatter focuses specifically on formatting ERB templates, which are commonly used in Rails views. It ensures consistent indentation, spacing, and HTML structure in your template files.
Installation
Installing RuboCop
The simplest way to install RuboCop is via RubyGems:
gem install rubocop
For a Rails project, add it to your Gemfile:
# Gemfile
group :development do
gem 'rubocop', require: false
gem 'rubocop-rails', require: false # Rails-specific extension
gem 'rubocop-rspec', require: false # Optional: RSpec extension
gem 'rubocop-performance', require: false # Optional: Performance extension
end
Then run bundle install:
bundle install
Installing ERB-Formatter
To install the ERB-Formatter:
gem install erb_formatter
Or add it to your Gemfile:
# Gemfile
group :development do
gem 'erb_formatter', require: false
end
Then run bundle install:
bundle install
Basic Usage
Using RuboCop
To analyze all Ruby files in your project with RuboCop:
rubocop
To analyze specific files or directories:
rubocop app/models app/controllers/users_controller.rb
The output will show violations with their severity levels, filenames, line numbers, and explanations:
Inspecting 15 files
.C..C....C...W.
app/controllers/users_controller.rb:15:3: C: Layout/SpaceAroundOperators: Surrounding space missing for operator '+'.
@user = User.find(params[:id])+ current_user
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
app/models/user.rb:5:5: W: Metrics/MethodLength: Method has too many lines. [15/10]
def complex_method
^^^^^^^^^^^^^^^^^
The output uses these indicators:
-
.
- No offenses -
C
- Convention violation (style issues) -
W
- Warning (potential problems) -
E
- Error (likely bugs) -
F
- Fatal error (syntax errors, etc.)
Using ERB-Formatter
To format all ERB files in your project:
erb_formatter .
To format specific files:
erb_formatter app/views/users/index.html.erb
By default, ERB-Formatter will modify files in place. To check what would be changed without modifying files:
erb_formatter --check app/views/**/*.erb
Auto-correction with RuboCop
RuboCop can automatically fix many offenses with the{" "}
-a
or --auto-correct
flag:
rubocop --auto-correct
For more aggressive auto-correction, including potentially unsafe fixes:
rubocop --auto-correct-all
To only show offenses that can be auto-corrected:
rubocop --auto-correct --only-correctable
Configuration
.rubocop.yml Configuration
RuboCop's behavior is customized through a{" "}
.rubocop.yml
file in your project's root directory:
AllCops:
NewCops: enable
TargetRubyVersion: 3.1
Exclude:
- 'db/**/*'
- 'bin/**/*'
- 'vendor/**/*'
Style/StringLiterals:
EnforcedStyle: single_quotes
Layout/LineLength:
Max: 100
Metrics/MethodLength:
Max: 15
Style/Documentation:
Enabled: false
This example configuration:
- Enables new cops introduced in newer RuboCop versions
- Sets the target Ruby version to 3.1
- Excludes certain directories from inspection
- Enforces single quotes for string literals
- Sets maximum line length to 100 characters
- Allows methods up to 15 lines
- Disables documentation requirement
Configuration Inheritance
You can inherit from existing configurations using the{" "}
inherit_from
directive:
inherit_from:
- .rubocop_base.yml
- .rubocop_strict.yml
# Overrides or additional configurations...
You can also inherit from remote configurations:
inherit_from:
- https://raw.githubusercontent.com/rails/rails/master/.rubocop.yml
Customizing Rules
For each cop, you can:
-
Enable or disable it with
Enabled: true/false
- Configure its behavior with cop-specific parameters
- Include or exclude specific files for that cop
- Set the severity level (refactor, convention, warning, error, fatal)
Example of detailed cop configuration:
Style/NumericLiterals:
Enabled: true
MinDigits: 5
Strict: false
Exclude:
- 'spec/**/*'
Severity: warning
Rails-Specific Configuration
For Rails projects, enable the Rails cops:
require:
- rubocop-rails
Rails:
Enabled: true
Rails/TimeZone:
Enabled: true
EnforcedStyle: strict
Rails/HasManyOrHasOneDependent:
Enabled: true
Rails/SkipsModelValidations:
Enabled: true
Exclude:
- 'spec/**/*'
This configuration:
- Requires the rubocop-rails extension
- Enables all Rails cops
- Enforces strict Time zone handling
- Ensures dependent options on associations
- Flags uses of methods that skip validations (except in specs)
Code Examples
Let's look at some examples of how RuboCop and ERB-Formatter transform code:
Ruby Formatting Examples
The formatted code includes proper:
- Spacing around operators and after colons
- Consistent indentation (2 spaces)
- Space around inheritance operator
- Parentheses for method parameters
- String interpolation instead of concatenation
- Single quotes for strings without interpolation
ERB Template Formatting
ERB-Formatter ensures:
- Consistent indentation for HTML elements
- Proper indentation of Ruby blocks within ERB tags
- Consistent spacing in HTML attributes
- Clean nesting of HTML elements
Rails-Specific Formatting
RuboCop with Rails enabled catches Rails-specific issues like:
-
Using
render :new
instead of{" "}render action: "new"
-
Adding a
post_params
method for strong parameters -
Marking helper methods as
private
- Spacing around assignment operators
Editor Integration
Integrating RuboCop and ERB-Formatter with your editor allows for real-time feedback and automatic formatting.
Visual Studio Code
For VS Code, install the following extensions:
Configure your settings.json:
{
"editor.formatOnSave": true,
"ruby.format": "rubocop",
"ruby.rubocop.executePath": "/usr/local/bin/",
"ruby.rubocop.onSave": true,
"emmet.includeLanguages": {
"erb": "html"
},
"[erb]": {
"editor.defaultFormatter": "aliariff.vscode-erb-beautify"
}
}
RubyMine
RubyMine includes built-in support for RuboCop. To configure it:
- Go to Settings/Preferences {">"} Editor {">"} Inspections {">"}{" "} Ruby {">"} Gems and Gem Management
- Enable "RuboCop" and "ERB/Rails/I18n best practices"
- Configure RuboCop path and options in the settings panel
To enable format on save:
- Go to Settings/Preferences {">"} Tools {">"} File Watchers
- Add a new watcher for RuboCop and ERB-Formatter
Vim and Neovim
For Vim, you can use plugins like ALE (Asynchronous Lint Engine) or Syntastic:
" For ALE
let g:ale_fixers = {
\ 'ruby': ['rubocop'],
\ 'eruby': ['erb_formatter'],
\}
let g:ale_fix_on_save = 1
" For Syntastic
let g:syntastic_ruby_checkers = ['rubocop']
let g:syntastic_eruby_checkers = ['erb_formatter']
For Neovim with LSP, configure solargraph or ruby-lsp with RuboCop integration.
Automating Formatting
Git Pre-commit Hooks
You can use pre-commit hooks to ensure all committed code is properly formatted. Install overcommit gem:
gem install overcommit
Initialize overcommit in your project:
overcommit --install
Configure .overcommit.yml:
PreCommit:
RuboCop:
enabled: true
command: ['bundle', 'exec', 'rubocop']
on_warn: fail
include:
- '**/*.rb'
- '**/*.rake'
- 'Gemfile'
ErbFormatter:
enabled: true
command: ['bundle', 'exec', 'erb_formatter', '--check']
on_warn: fail
include:
- '**/*.erb'
CI/CD Integration
Add formatting checks to your CI pipeline to catch issues early. Example for GitHub Actions:
name: Ruby Linting
on:
push:
branches: [ main ]
pull_request:
branches: [ main ]
jobs:
lint:
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v3
- name: Set up Ruby
uses: ruby/setup-ruby@v1
with:
ruby-version: 3.1
bundler-cache: true
- name: Install dependencies
run: |
gem install rubocop
gem install erb_formatter
- name: Lint Ruby Files
run: rubocop
- name: Lint ERB Files
run: erb_formatter --check app/views/**/*.erb
Best Practices
To get the most out of your Ruby formatting tools:
- Start with a base configuration that's close to the Ruby community standards, then customize as needed
- Version control your configuration files to ensure consistency across all developers
- Gradually introduce formatting to existing projects to avoid massive, disruptive changes
- Automate formatting checks in CI/CD pipelines and pre-commit hooks
- Configure your editor for real-time feedback and auto-correction
- Periodically update RuboCop to benefit from new rules and improvements
-
Use RuboCop's auto-generation feature for
creating an initial configuration based on your existing code:
rubocop --auto-gen-config
Troubleshooting Common Issues
When working with RuboCop and ERB-Formatter, you might encounter these common issues:
Issue | Solution |
---|---|
RuboCop running slowly |
Use --parallel flag or --cache {" "}
for incremental analysis
|
Too many offenses |
Start with --auto-gen-config and gradually
address issues
|
Auto-correction breaking code |
Use --safe-auto-correct and review changes
before committing
|
ERB-Formatter not finding files | Check file extensions (.erb, .html.erb) and use proper glob patterns |
Bundler conflicts |
Use bundle exec rubocop to ensure right
version is used
|
Future Development
The Ruby formatting ecosystem continues to evolve:
- RuboCop regularly adds new cops and capabilities with each release
- New extensions like rubocop-performance and rubocop-rspec expand coverage
- The community is working on improving performance for large codebases
- Integration with Ruby's official LSP (Language Server Protocol) is improving
Stay updated with new releases and consider contributing to these open-source projects if you find issues or have improvements to suggest.
Conclusion
Consistent code formatting may seem like a small detail, but it significantly impacts readability, maintainability, and overall code quality. By leveraging RuboCop and ERB-Formatter, you can ensure your Ruby and Rails projects maintain a consistent style that adheres to community best practices.
Remember that while these tools provide excellent defaults, the best configuration is one that works for your team. Don't be afraid to customize rules to suit your specific needs, but try to stay reasonably close to community standards to ensure your code remains accessible to other Ruby developers.
With automated formatting integrated into your workflow, you can focus on what really matters: writing robust, efficient Ruby code that solves real problems.