Ruby Community Style Guide
Overview
This skill provides comprehensive guidance for writing idiomatic Ruby code that strictly follows the RuboCop Community Ruby Style Guide - the most widely adopted Ruby style guide in the community (16.5k GitHub stars). It emphasizes readability, consistency, proper use of Ruby idioms, Test-Driven Development, and Ruby's philosophy of developer happiness.
When to Use This Skill
Use this skill for any Ruby-related programming task:
- Writing new Ruby code or implementing new features
- Reviewing existing Ruby code for best practices and idioms
- Refactoring code to follow Ruby Community Style Guide
- Debugging Ruby applications and fixing issues
- Working with Rails, Sinatra, or other Ruby frameworks
- Designing Ruby APIs and gem structures
- Implementing tests with RSpec or Minitest
Core Ruby Philosophy
Mandatory Principles
1. Matz's Philosophy: Optimize for Developer Happiness
- Ruby is designed to make programmers happy
- Code should be readable and expressive
- Prefer clarity over cleverness
- Follow the Principle of Least Surprise
2. Test-Driven Development (TDD)
- Write tests first using Red-Green-Refactor cycle
- Use RSpec or Minitest for comprehensive test coverage
- Tests must be in place before implementation code
3. Sandi Metz Rules (Structural Limits)
- Classes: ≤100 lines per class
- Methods: ≤5 lines per method
- Parameters: ≤4 parameters per method (use keyword arguments for more)
- Controllers: ≤1 instance variable passed to views
- Break limits only with explicit documentation and approval
4. Duck Typing Over Type Checking
- Favor duck typing; avoid explicit type checking
- Program to behaviors, not types
- Use
respond_to? only when truly necessary
Workflow
For Writing New Ruby Code
Write the test first (TDD mandatory)
- Define expected behavior in RSpec or Minitest
- Run test to see it fail (Red)
Implement minimal code to pass the test (Green)
- Write just enough code to make the test pass
- Follow Ruby Community Style Guide conventions
Refactor while keeping tests green
- Improve code quality, readability, and performance
- Ensure all tests still pass
Verify quality standards
- Run
rubocop to check style compliance
- Run
bundle exec rspec or bundle exec rake test
- Check Sandi Metz rules (≤100 lines/class, ≤5 lines/method)
For Code Review
Check TDD compliance
- Verify tests exist and are comprehensive
- Ensure proper test structure (describe/context/it)
Review Ruby Community Style Guide compliance
- Run RuboCop and address all offenses
- Verify naming conventions (snake_case, CamelCase)
- Confirm proper use of Ruby idioms
Validate structural limits
- Classes ≤100 lines
- Methods ≤5 lines
- ≤4 parameters per method
- Single Responsibility Principle adherence
Check for Ruby-specific issues
- Prefer && and || operators over
and/or keywords in conditions
- Use guard clauses instead of nested conditionals
- Verify proper exception handling patterns
- Check for proper use of blocks and iterators
For Refactoring
Ensure tests exist first
- If no tests, write them before refactoring
- Tests provide safety net during refactoring
Identify anti-patterns
- Methods >5 lines
- Classes >100 lines
- God classes with too many responsibilities
- Excessive metaprogramming
- Type checking (
is_a?, kind_of?) instead of duck typing
Refactor incrementally
- Extract methods for long code blocks
- Extract classes for multiple responsibilities
- Keep tests passing after each change
Key Style Rules Summary
Naming Conventions
snake_case for methods, variables, symbols, files
CamelCase for classes and modules
SCREAMING_SNAKE_CASE for constants
- End predicates with ? suffix (e.g.,
empty?, valid?)
- End dangerous/mutating methods with bang suffix (!) when a safe version exists
- Avoid get_/set_/is_ prefixes
Formatting
- 2 spaces for indentation (no tabs)
- UTF-8 encoding
- Maximum 80-120 characters per line (80 preferred)
- Unix-style line endings (LF)
- One expression per line
Method Design
- Omit
return when unnecessary (implicit returns)
- Omit
self except for setters
- Use guard clauses for early returns
- Use keyword arguments for optional parameters
- Avoid more than 4 parameters (use keyword args or objects)
Collections & Iteration
- Prefer
map/select/reduce over each with mutation
- Use
%w[] for word arrays, %i[] for symbol arrays
- Use
Hash#fetch with defaults instead of || operator
- Prefer
first/last over [0]/[-1]
Strings
- Use string interpolation
"Hello, #{name}" over concatenation
- Use double quotes consistently (Shopify) or single when no interpolation (Community)
- Use heredocs (
<<~) for multi-line strings
- Prefer
String#chars over split('')
Exceptions
- Use
raise over fail
- Never rescue
Exception class (use StandardError)
- Provide meaningful error messages
- Use implicit begin blocks in methods
Reference Materials
For detailed code patterns, examples, and guidelines, consult the reference files:
references/ruby-patterns.md - Comprehensive Ruby style patterns and anti-patterns
- Source layout, naming conventions, syntax preferences
- Method definitions, control flow, operators
- Comments and documentation guidelines
references/classes-modules.md - OOP patterns in Ruby
- Class structure and organization
- Module design and mixins
- Inheritance vs composition
- Access modifiers and visibility
references/testing-patterns.md - Ruby testing best practices
- RSpec patterns and conventions
- Minitest patterns
- Test organization and structure
- Mocking and stubbing guidelines
Use grep to search these files for specific patterns when needed (e.g., search for "guard clause", "keyword arguments", or "let vs before").
Template Assets
Pre-built templates are available in assets/templates/ for common Ruby patterns:
assets/templates/class_template.rb - Standard class structure with Sandi Metz compliance
assets/templates/service_object.rb - Service object pattern template
assets/templates/rspec_spec.rb - RSpec test file template
assets/templates/minitest_test.rb - Minitest test file template
Copy and customize these templates as starting points for new code.
Quality Assurance Checklist
Before delivering Ruby code, verify:
Critical Ruby Style Rules:
Sandi Metz Rules:
Code Quality:
Ruby Idioms:
Testing:
Communication Guidelines
When providing Ruby coding assistance:
- Reference RuboCop Community Style Guide for rationale
- Provide working, tested code examples
- Explain Ruby idioms and their benefits
- Suggest RuboCop cops for common violations
- Point out Ruby-specific pitfalls and solutions
- Prioritize Ruby's philosophy of expressiveness and readability
Key Differences from General Coding Principles
This skill overrides some general coding principles with Ruby-specific rules:
- Method length: 5 lines (vs. general 20 lines) - Sandi Metz rules are stricter
- Class length: 100 lines (vs. general 500 lines) - Ruby favors small, focused classes
- Implicit returns: No explicit
return statement - unlike most languages
- Testing approach: TDD is mandatory with RSpec/Minitest patterns
- Parameter limits: Strict ≤4 parameter limit with keyword arguments as solution
1---2name: ruby-community-style3description: Use this skill when writing Ruby code following the RuboCop Community Ruby Style Guide. Provides comprehensive guidance on idiomatic Ruby patterns, method design, class structure, collections, strings, exceptions, and testing. Covers Sandi Metz rules, duck typing, metaprogramming guidelines, and RuboCop enforcement. Appropriate for any task involving .rb files, Ruby code reviews, refactoring, Rails development, or implementing Ruby best practices.4---5
6# Ruby Community Style Guide
7
8## Overview
9
10This skill provides comprehensive guidance for writing idiomatic Ruby code that strictly follows the RuboCop Community Ruby Style Guide - the most widely adopted Ruby style guide in the community (16.5k GitHub stars). It emphasizes readability, consistency, proper use of Ruby idioms, Test-Driven Development, and Ruby's philosophy of developer happiness.
11
12## When to Use This Skill
13
14Use this skill for any Ruby-related programming task:
15- Writing new Ruby code or implementing new features
16- Reviewing existing Ruby code for best practices and idioms
17- Refactoring code to follow Ruby Community Style Guide
18- Debugging Ruby applications and fixing issues
19- Working with Rails, Sinatra, or other Ruby frameworks
20- Designing Ruby APIs and gem structures
21- Implementing tests with RSpec or Minitest
22
23## Core Ruby Philosophy
24
25### Mandatory Principles
26
27**1. Matz's Philosophy: Optimize for Developer Happiness**
28- Ruby is designed to make programmers happy
29- Code should be readable and expressive
30- Prefer clarity over cleverness
31- Follow the Principle of Least Surprise
32
33**2. Test-Driven Development (TDD)**
34- Write tests first using Red-Green-Refactor cycle
35- Use RSpec or Minitest for comprehensive test coverage
36- Tests must be in place before implementation code
37
38**3. Sandi Metz Rules (Structural Limits)**
39- Classes: ≤100 lines per class
40- Methods: ≤5 lines per method
41- Parameters: ≤4 parameters per method (use keyword arguments for more)
42- Controllers: ≤1 instance variable passed to views
43- Break limits only with explicit documentation and approval
44
45**4. Duck Typing Over Type Checking**
46- Favor duck typing; avoid explicit type checking
47- Program to behaviors, not types
48- Use `respond_to?` only when truly necessary
49
50## Workflow
51
52### For Writing New Ruby Code
53
541. **Write the test first** (TDD mandatory)
55 - Define expected behavior in RSpec or Minitest
56 - Run test to see it fail (Red)
57
582. **Implement minimal code to pass the test** (Green)
59 - Write just enough code to make the test pass
60 - Follow Ruby Community Style Guide conventions
61
623. **Refactor while keeping tests green**
63 - Improve code quality, readability, and performance
64 - Ensure all tests still pass
65
664. **Verify quality standards**
67 - Run `rubocop` to check style compliance
68 - Run `bundle exec rspec` or `bundle exec rake test`
69 - Check Sandi Metz rules (≤100 lines/class, ≤5 lines/method)
70
71### For Code Review
72
731. **Check TDD compliance**
74 - Verify tests exist and are comprehensive
75 - Ensure proper test structure (describe/context/it)
76
772. **Review Ruby Community Style Guide compliance**
78 - Run RuboCop and address all offenses
79 - Verify naming conventions (snake_case, CamelCase)
80 - Confirm proper use of Ruby idioms
81
823. **Validate structural limits**
83 - Classes ≤100 lines
84 - Methods ≤5 lines
85 - ≤4 parameters per method
86 - Single Responsibility Principle adherence
87
884. **Check for Ruby-specific issues**
89 - Prefer && and || operators over `and`/`or` keywords in conditions
90 - Use guard clauses instead of nested conditionals
91 - Verify proper exception handling patterns
92 - Check for proper use of blocks and iterators
93
94### For Refactoring
95
961. **Ensure tests exist first**
97 - If no tests, write them before refactoring
98 - Tests provide safety net during refactoring
99
1002. **Identify anti-patterns**
101 - Methods >5 lines
102 - Classes >100 lines
103 - God classes with too many responsibilities
104 - Excessive metaprogramming
105 - Type checking (`is_a?`, `kind_of?`) instead of duck typing
106
1073. **Refactor incrementally**
108 - Extract methods for long code blocks
109 - Extract classes for multiple responsibilities
110 - Keep tests passing after each change
111
112## Key Style Rules Summary
113
114### Naming Conventions
115- `snake_case` for methods, variables, symbols, files
116- `CamelCase` for classes and modules
117- `SCREAMING_SNAKE_CASE` for constants
118- End predicates with ? suffix (e.g., `empty?`, `valid?`)
119- End dangerous/mutating methods with bang suffix (!) when a safe version exists
120- Avoid get_/set_/is_ prefixes
121
122### Formatting
123- 2 spaces for indentation (no tabs)
124- UTF-8 encoding
125- Maximum 80-120 characters per line (80 preferred)
126- Unix-style line endings (LF)
127- One expression per line
128
129### Method Design
130- Omit `return` when unnecessary (implicit returns)
131- Omit `self` except for setters
132- Use guard clauses for early returns
133- Use keyword arguments for optional parameters
134- Avoid more than 4 parameters (use keyword args or objects)
135
136### Collections & Iteration
137- Prefer `map`/`select`/`reduce` over `each` with mutation
138- Use `%w[]` for word arrays, `%i[]` for symbol arrays
139- Use `Hash#fetch` with defaults instead of || operator
140- Prefer `first`/`last` over `[0]`/`[-1]`
141
142### Strings
143- Use string interpolation `"Hello, #{name}"` over concatenation
144- Use double quotes consistently (Shopify) or single when no interpolation (Community)
145- Use heredocs (`<<~`) for multi-line strings
146- Prefer `String#chars` over `split('')`
147
148### Exceptions
149- Use `raise` over `fail`
150- Never rescue `Exception` class (use `StandardError`)
151- Provide meaningful error messages
152- Use implicit begin blocks in methods
153
154## Reference Materials
155
156For detailed code patterns, examples, and guidelines, consult the reference files:
157
158- `references/ruby-patterns.md` - Comprehensive Ruby style patterns and anti-patterns
159 - Source layout, naming conventions, syntax preferences
160 - Method definitions, control flow, operators
161 - Comments and documentation guidelines
162- `references/classes-modules.md` - OOP patterns in Ruby
163 - Class structure and organization
164 - Module design and mixins
165 - Inheritance vs composition
166 - Access modifiers and visibility
167- `references/testing-patterns.md` - Ruby testing best practices
168 - RSpec patterns and conventions
169 - Minitest patterns
170 - Test organization and structure
171 - Mocking and stubbing guidelines
172
173Use grep to search these files for specific patterns when needed (e.g., search for "guard clause", "keyword arguments", or "let vs before").
174
175## Template Assets
176
177Pre-built templates are available in `assets/templates/` for common Ruby patterns:
178
179- `assets/templates/class_template.rb` - Standard class structure with Sandi Metz compliance
180- `assets/templates/service_object.rb` - Service object pattern template
181- `assets/templates/rspec_spec.rb` - RSpec test file template
182- `assets/templates/minitest_test.rb` - Minitest test file template
183
184Copy and customize these templates as starting points for new code.
185
186## Quality Assurance Checklist
187
188Before delivering Ruby code, verify:
189
190**Critical Ruby Style Rules:**
191- [ ] 2-space indentation (no tabs)
192- [ ] snake_case for methods/variables, CamelCase for classes
193- [ ] Predicates end with ? suffix, dangerous methods with ! suffix
194- [ ] No explicit `return` unless required for early exit
195- [ ] No explicit `self` unless required (setters, disambiguation)
196- [ ] Use && and || for boolean logic (not `and`/`or`)
197- [ ] Guard clauses instead of nested conditionals
198- [ ] Iterators (`map`, `select`, `reduce`) over `for` loops
199
200**Sandi Metz Rules:**
201- [ ] Classes ≤100 lines
202- [ ] Methods ≤5 lines
203- [ ] ≤4 parameters per method (use keyword arguments for more)
204- [ ] ≤1 instance variable per controller action (Rails)
205
206**Code Quality:**
207- [ ] Tests written first (TDD followed)
208- [ ] RuboCop passes with no offenses
209- [ ] Tests pass with `bundle exec rspec` or `rake test`
210- [ ] Proper exception handling (no bare `rescue`)
211- [ ] No commented-out code
212
213**Ruby Idioms:**
214- [ ] Duck typing preferred over type checking
215- [ ] String interpolation over concatenation
216- [ ] Use `Hash#fetch` with defaults over || operator
217- [ ] Use `%w[]` and `%i[]` for word/symbol arrays
218- [ ] Blocks use `{}` for single-line, `do...end` for multi-line
219
220**Testing:**
221- [ ] One assertion per test (when possible)
222- [ ] Descriptive test names (`it "returns nil when user not found"`)
223- [ ] Proper use of let/let! vs before in RSpec
224- [ ] Test edge cases and error conditions
225
226## Communication Guidelines
227
228When providing Ruby coding assistance:
229- Reference RuboCop Community Style Guide for rationale
230- Provide working, tested code examples
231- Explain Ruby idioms and their benefits
232- Suggest RuboCop cops for common violations
233- Point out Ruby-specific pitfalls and solutions
234- Prioritize Ruby's philosophy of expressiveness and readability
235
236## Key Differences from General Coding Principles
237
238This skill overrides some general coding principles with Ruby-specific rules:
239- **Method length**: 5 lines (vs. general 20 lines) - Sandi Metz rules are stricter
240- **Class length**: 100 lines (vs. general 500 lines) - Ruby favors small, focused classes
241- **Implicit returns**: No explicit `return` statement - unlike most languages
242- **Testing approach**: TDD is mandatory with RSpec/Minitest patterns
243- **Parameter limits**: Strict ≤4 parameter limit with keyword arguments as solution