/rails-cto:rails-cto-static-analysisfrom rails-cto
Runs Reek, Flog, and Flay static analysis on changed Ruby files and auto-refactors code smells, complexity, and duplication. Also enforces method documentation comments.
Ships in rails-cto. Installing the plugin adds it to Claude Code.
What the skill costs in Claude's context, stage by stage
Name and description: Claude knows it exists.
SKILL.md joins the conversation and stays.
None: SKILL.md is the whole skill.
Every .rb change is analyzed with Reek, Flog, and Flay before the work is considered done. Code smells are fixed, complex methods are refactored, and duplication is eliminated. This skill runs before RuboCop and tests — refactor first, then lint and verify.
Before running any analysis, verify each tool is installed. Run all three checks:
bundle exec reek --version 2>/dev/null
bundle exec ruby -e "require 'flog'" 2>/dev/null
bundle exec flay --version 2>/dev/null
Note: Flog does not support a --version flag. Use require 'flog' to verify it's installed.
If a tool is not available, print this message and skip that tool's steps (but continue with the others):
[tool]is not installed. Add it to your Gemfile under:development:gem "[tool]", require: falseThen run
bundle install.
If none of the three tools are available, stop and inform the user that static analysis cannot run.
.reek.yml if missingCheck for a Reek configuration file:
ls .reek.yml 2>/dev/null
If .reek.yml does not exist, create it with the Rails-friendly defaults from the Configuration section below. If it already exists, leave it as-is.
Collect all .rb files that have been created or modified:
git diff --name-only --diff-filter=ACMR HEAD 2>/dev/null | grep -E '\.rb$' | sort -u
git diff --name-only --diff-filter=ACMR 2>/dev/null | grep -E '\.rb$' | sort -u
Combine and deduplicate both lists. If no .rb files changed, skip all scans and report "No Ruby files changed — static analysis skipped."
Every Ruby method must have a comment directly above the def line describing why it exists — not what it does (the code shows that). Focus on intent, context, or the business reason.
For each changed .rb file, scan for def declarations and verify a comment appears on the line(s) immediately above. If any methods are missing a comment, add one before proceeding.
# Ensures the user sees their most relevant posts first,
# because recently active tags reflect current interests.
def prioritized_posts
posts.joins(:tags).order("tags.updated_at DESC")
end
# Strips tracking parameters so we store clean URLs
# and don't leak referral data to downstream services.
def sanitize_url(url)
URI.parse(url).tap { |u| u.query = nil }.to_s
end
Do not add comments to trivial or framework-conventional methods where intent is self-evident:
initialize with simple assignmentdelegate :name, to: :user)def name = @name)before_save :normalize_email)super-only overridesit, test, describe blocks)For each undocumented method, read the method body and write a one-line comment explaining why the method exists. If the reason isn't clear from context, write what it does and flag it for the user to refine. After adding comments, move on to Reek.
Run Reek on each changed file individually:
bundle exec reek path/to/changed_file.rb
For multiple changed files:
bundle exec reek app/models/user.rb app/commands/users/create.rb app/controllers/users_controller.rb
Reek reports warnings in this format:
app/models/user.rb -- 2 warnings:
[4]:UncommunicativeMethodName: User#x has the name 'x'
[12]:TooManyStatements: User#process has approx 15 statements
Use this table to decide what to fix and how:
| Smell | When it's real | Auto-fix |
|---|---|---|
TooManyStatements | > 10 statements in a non-migration method | Extract into private methods or a service/command object |
LongParameterList | > 4 parameters | Introduce keyword arguments or a parameter object |
FeatureEnvy | Method uses another object's data more than its own | Move the method to the object it references most |
DataClump | 3+ methods share the same parameter group | Extract a value object |
DuplicateMethodCall | Same call appears 3+ times in one method | Extract to a local variable |
UncommunicativeVariableName | Single-letter or cryptic names | Rename to something descriptive |
UncommunicativeMethodName | Single-letter or cryptic names | Rename to something descriptive |
NilCheck | Explicit nil? checks | Fix only if it masks a real nil-safety issue — often noise in Rails |
UtilityFunction | Method doesn't use self | Fix in models and services; ignore in helpers and decorators |
TooManyInstanceVariables | > 6 instance variables in a class | Extract a value object or split responsibilities |
TooManyMethods | > 20 methods in a class | Extract concerns or split into smaller classes |
ControlCouple | Method behavior depends on a boolean/flag arg | Replace with two methods or use polymorphism — ignore in controllers |
BooleanParameter | def method(flag = true) | Replace with two methods — ignore in controllers and helpers |
Run Flog on each changed file individually:
bundle exec flog path/to/changed_file.rb
Flog outputs a pain score per method, sorted by complexity:
47.2: User#process app/models/user.rb:12-45
18.3: User#validate_email app/models/user.rb:50-62
6.1: User#name app/models/user.rb:8-10
Higher scores mean more complex, harder-to-maintain code.
| Score | Verdict | Action |
|---|---|---|
| ≤ 10 | Trivial | No action needed |
| 11–25 | Acceptable | No action needed |
| 26–60 | Too complex | Must refactor — extract methods, simplify conditionals, reduce nesting |
| > 60 | Severe | Stop and refactor immediately — this method is a maintenance hazard |
For methods scoring above 25:
if/else with guard clauses, early returns, or case statements.If the score remains above 25 after one refactoring pass, report the method and its score to the user and move on.
Flay identifies structural similarities in code, ignoring surface-level differences like variable names, literal values, and whitespace.
For each changed .rb file, collect its sibling files:
app/models/ for app/models/user.rb)..rb files in that directory..rb files, limit to the changed file plus the 10 most recently modified siblings:
ls -t app/models/*.rb | head -10
.rb file exists in the directory, skip Flay for that file — duplication detection requires at least two files.bundle exec flay app/models/*.rb
Or with a specific set of files:
bundle exec flay app/models/user.rb app/models/account.rb app/models/profile.rb
Flay reports structural duplication with a mass score:
1) IDENTICAL code found in :defn (mass = 72)
app/models/user.rb:15
app/models/account.rb:22
2) Similar code found in :defn (mass = 32)
app/controllers/users_controller.rb:10
app/controllers/accounts_controller.rb:12
| Mass | Verdict | Action |
|---|---|---|
| < 16 | Insignificant | No action needed |
| 16–50 | Moderate duplication | Extract shared logic into a concern, module, or shared method |
| > 50 | Significant duplication | Must extract — this is copy-paste code that will drift |
For nodes with mass ≥ 16:
app/models/concerns/app/controllers/concerns/If the duplication spans fundamentally different contexts where extraction would be forced or artificial, report it to the user instead of extracting.
After all three tools have run and fixes have been applied:
**Static Analysis Summary**
- Reek: N smells found, N fixed, N remaining
- Flog: N methods above threshold (25), N refactored
- Flay: N duplications (mass ≥ 16), N extracted
- Status: PASS / NEEDS ATTENTION
PASS means all issues were resolved or no issues were found. NEEDS ATTENTION means some issues remain that require manual intervention — list them with file, line, and description.
.reek.yml — Rails-friendly defaultsIf the project has no .reek.yml, create this file in the project root:
---
# Rails-friendly Reek configuration
# Generated by rails-cto-static-analysis
detectors:
IrresponsibleModule:
enabled: false
InstanceVariableAssumption:
enabled: false
TooManyStatements:
max_statements: 10
ControlCouple:
exclude:
- !ruby/regexp /app\/controllers/
BooleanParameter:
exclude:
- !ruby/regexp /app\/controllers/
- !ruby/regexp /app\/helpers/
FeatureEnvy:
exclude:
- !ruby/regexp /app\/helpers/
- !ruby/regexp /app\/decorators/
UtilityFunction:
exclude:
- !ruby/regexp /app\/helpers/
- !ruby/regexp /app\/decorators/
UncommunicativeMethodName:
accept:
- e
- t
- q
- x
- y
LongParameterList:
max_params: 4
TooManyInstanceVariables:
max_instance_variables: 6
TooManyMethods:
max_methods: 20
directories:
"test":
enabled: false
"db/migrate":
TooManyStatements:
enabled: false
FeatureEnvy:
enabled: false
| Tool | Metric | Threshold | Action |
|---|---|---|---|
| Reek | Code smell | Any warning | Auto-fix per interpretation table |
| Flog | Method complexity | > 25 per method | Must refactor |
| Flog | Severe complexity | > 60 per method | Stop and refactor immediately |
| Flay | Structural duplication | Mass ≥ 16 | Extract shared logic |
| Task | Command |
|---|---|
| Scan one file for smells | bundle exec reek path/to/file.rb |
| Scan one file for complexity | bundle exec flog path/to/file.rb |
| Scan directory for duplication | bundle exec flay path/to/dir/*.rb |
| Scan specific files for duplication | bundle exec flay file1.rb file2.rb |
What SKILL.md sets; muted values are Claude Code's defaults
Three short reads, in order
npx claudepluginhub mattsears/rails-cto --plugin rails-cto17 skills in this plugin
/rails-ctoOrchestrator skill for Ruby on Rails projects. Initializes sessions, routes to specialized skills, enforces mandatory QA gates, and runs the completion checklist. Invoke at the start of every Rails session./rails-cto-apiHow to build RESTful JSON APIs in a Rails 8 application following OpenAPI standards. Use when creating, modifying, or debugging API endpoints, serializers, authentication, documentation, or any code under the Api:: namespace. Also use when the user mentions "api", "endpoint", "api key", "serializer", "openapi", "swagger", "api documentation", "cors", "rate limit", "pagination cursor", "api versioning", or asks about exposing data to external consumers. Proactively apply these rules whenever touching API controllers, routes, or serializers, even if the user doesn't explicitly ask.
/rails-cto-architectHow to write comprehensive implementation plans for multi-step Rails features before any code is written. Use when the user has a spec, feature request, or multi-step task and wants to plan the approach before touching code. Also use when the user mentions "create a plan", "write a plan", "plan this", "plan a feature", "implementation plan", "build a new feature", "new feature", "how should I build", "how do I build", "architect this", "design this", "design a feature", "feature design", "spec", "requirements", or pastes long-form requirements. Proactively invoke this skill BEFORE writing any code for multi-file or multi-step work, even if the user doesn't explicitly say "plan" — every multi-step feature goes through architect first. Produces a bite-sized, task-by-task plan optimized for rails-cto-engineer to execute. Never writes code, never commits, and never generates plans that contain commit steps.
/rails-cto-commitStage and commit all outstanding code changes with a clear, human-friendly commit message. Use this skill whenever the user asks to commit, save their work, push changes, or says things like "commit this", "save my progress", "push this up", "ship it", "commit all", or "commit and push". Also triggers for "/commit-all". Do NOT use for cherry-picking, rebasing, or other advanced git operations./rails-cto-engineerThis file provides guidance to Claude Code (claude.ai/code) when working with Ruby on Rails projects./rails-cto-erbHow to write clean, well-formatted ERB templates for this Rails 8 project. Use when creating or modifying any ERB view, partial, layout, or component template. Also use when the user mentions "erb", "views", "partials", "templates", "html formatting", "attribute alignment", or asks about view-layer code. Proactively apply these rules whenever touching .html.erb files, even if the user doesn't explicitly ask for formatting help.
Other plugins' skills for the same job