Write idiomatic Ruby (and Rails)
Ruby's expressiveness helps readers when objects are small, named well and follow the
idioms the repo already uses; it hurts when metaprogramming hides behaviour or Rails
conventions are fought. For the builder and the reviewer of a Ruby diff; the repo's config and existing code win over it.
Procedure
- Discover the repo's conventions first. Call
search_lore for Ruby conventions.
Read .ruby-version/.tool-versions, Gemfile and Gemfile.lock, .rubocop.yml
(and inherit_from/inherit_gem: Standard, rubocop-rails-omakase, a
.rubocop_todo.yml), .standard.yml, type tooling (sorbet/, sig/ for RBS), .rspec
or test/, config/application.rb (load_defaults), the job adapter and the CI
workflow. Identify the service/query/form object patterns and factories. Copy a sibling
class and its spec.
- Pin the exact commands from CI or
bin/ scripts (the run-tests and run-lint
skills). Use the defaults below only when the repo defines none. Never add offences to
.rubocop_todo.yml to pass.
- Write the change with the idioms below, then walk the concurrency section for every
shared object, record update, job, file and outbound call you touched.
- Test each acceptance criterion's own behaviour. One request/model/job spec (or
Minitest test) per AC that fails without your change, plus its error path. If the AC
involves shared state or persistence, add a test that runs N threads against it (each
with its own connection via
ActiveRecord::Base.connection_pool.with_connection, and
transactional fixtures disabled for that test) and asserts the invariant.
- Verify, then stop. Done when: RuboCop/Standard is clean, the suite is green, a new
migration migrates and rolls back, and every AC has a test. Record the output with the
record-evidence skill; the runner submits the work.
Commands
- Gems are already installed; never run
bundle install/bundle update/bundle add
(installs need human approval; the hook does not catch these, the rule still holds). A
missing gem goes in the evidence.
- Lint:
bundle exec rubocop (or bin/rubocop, bundle exec standardrb).
- Tests:
bundle exec rspec (one: bundle exec rspec spec/x_spec.rb:42) or bin/rails test (one: bin/rails test test/x_test.rb:42).
- Migrations:
bin/rails db:migrate then bin/rails db:rollback and migrate again,
only against the local development/test database; with none reachable, say so in the
evidence.
- Security and types where configured:
bundle exec brakeman, bundle exec bundle-audit check, bundle exec srb tc or bundle exec steep check.
Idioms that matter
- Small objects: single-purpose classes and short methods; service objects for
multi-step operations, query objects for complex reads, form objects for non-model
input; no fat models or controllers, no concern that exists only to split a huge class.
- Idiomatic Ruby (Ruby Style Guide):
each/map/select over for; guard clauses;
keyword arguments for more than two parameters; Data.define/Struct for simple values;
the # frozen_string_literal: true magic comment where the repo uses it; no
monkey-patching core classes; no method_missing/define_method without precedent.
- Rails the Rails way: validations in the model and constraints in the database
(
null: false, unique indexes, foreign keys — the add-db-migration skill); scopes for
reusable queries; strong parameters; includes/preload to kill N+1; ActiveJob for
async work (the background-jobs skill); I18n for user-visible strings (the i18n-l10n
skill).
- Errors: custom error classes under the app namespace;
rescue specific classes;
never rescue Exception (catches signals and exit) or rescue nil; re-raise with
context; result objects for expected failures where the repo uses them.
- Security by convention: parameterised queries (
where(id: v), where("x = ?", v)),
never interpolation; html_safe/raw only on sanitised content; YAML.safe_load, not
YAML.load/Marshal.load on untrusted data; no send/constantize on user input.
Concurrency and resource safety
- Puma and Sidekiq run your code on many threads. Class-level instance variables,
@@class_variables, constants holding mutable objects and class-level ||=
memoisation are shared across requests and race. Use request-scoped objects,
ActiveSupport::CurrentAttributes, or a Mutex held across the whole
read-modify-write.
- Lost updates on records: read, change in Ruby,
save loses concurrent writes. Use
record.with_lock { … }, optimistic locking (lock_version, rescue
ActiveRecord::StaleObjectError), or atomic SQL (increment!, Model.update_counters).
- Check-then-create races:
find_or_create_by can insert duplicates; back it with a
unique index and rescue ActiveRecord::RecordNotUnique (or create_or_find_by).
- Jobs and transactions: enqueue jobs and send mail in
after_commit (or after the
transaction), never inside it — the job can run before the row is visible or after a
rollback. Jobs are retried: make them idempotent.
- Files other requests read:
File.write is not atomic. Write to
Tempfile.create(["name", ".tmp"], File.dirname(target)) (unique, same filesystem), then
File.rename(tmp.path, target). Always use the block form of File.open. Cross-process
exclusion uses File#flock or the database; a time-only lease lets a paused holder write
late, so writes must check a version.
- Timeouts: set open/read timeouts on
Net::HTTP and client gems; do not use
Timeout.timeout around code that holds resources.
Review checklist — flag as defects
Walk this against the diff. An item is grounds for CHANGES only when, in changed code, it
causes a concrete failure (wrong result, crash, lost or corrupted data, security hole) or
leaves an AC's own behaviour untested: cite the line and that failure. Otherwise it is an
(optional) note. Formatting the tools would fix, and preferences the repo
does not enforce, are not findings. Do not patch the code under review.
Capture lore
This skill is one of the places durable, reusable knowledge naturally surfaces:
While matching the repo you learn the service, query and form object patterns, the job adapter and the RuboCop exceptions. That kind of fact is lore. Capture it via the lore-capture
protocol in your brief (CLAUDE.factory.md, step 11 "Memory contribution"):
call the Memory MCP suggest_lore once at the close of your work — reusable
conventions, gotchas, decisions, and boundaries only, never per-ticket trivia.
1---2name: ruby-conventions3description: Use when a ticket adds or changes Ruby code — Rails apps, gems, Rake tasks — and it must follow the repo's Ruby conventions — the Ruby Style Guide, small objects with clear responsibilities, Rails idioms where Rails is present (migrations, validations, scopes, jobs), thread-safe code under Puma and Sidekiq, no metaprogramming for its own sake, RuboCop/Standard clean — as the language pack for any Ruby change. Invoke for "add this in Rails", "fix the N+1", "the RuboCop offences", or when reviewing a Ruby diff.4stack: [ruby, rails]5area: language6metadata:7 source: https://skillmd.com/skills/tmj-90/ruby-conventions8---910# Write idiomatic Ruby (and Rails)1112Ruby's expressiveness helps readers when objects are small, named well and follow the13idioms the repo already uses; it hurts when metaprogramming hides behaviour or Rails14conventions are fought. For the builder and the reviewer of a Ruby diff; the repo's config and existing code win over it.1516## Procedure17181. **Discover the repo's conventions first.** Call `search_lore` for Ruby conventions.19 Read `.ruby-version`/`.tool-versions`, `Gemfile` and `Gemfile.lock`, `.rubocop.yml`20 (and `inherit_from`/`inherit_gem`: Standard, `rubocop-rails-omakase`, a21 `.rubocop_todo.yml`), `.standard.yml`, type tooling (`sorbet/`, `sig/` for RBS), `.rspec`22 or `test/`, `config/application.rb` (`load_defaults`), the job adapter and the CI23 workflow. Identify the service/query/form object patterns and factories. Copy a sibling24 class and its spec.252. **Pin the exact commands** from CI or `bin/` scripts (the `run-tests` and `run-lint`26 skills). Use the defaults below only when the repo defines none. Never add offences to27 `.rubocop_todo.yml` to pass.283. **Write the change with the idioms below**, then walk the concurrency section for every29 shared object, record update, job, file and outbound call you touched.304. **Test each acceptance criterion's own behaviour.** One request/model/job spec (or31 Minitest test) per AC that fails without your change, plus its error path. If the AC32 involves shared state or persistence, add a test that runs N threads against it (each33 with its own connection via `ActiveRecord::Base.connection_pool.with_connection`, and34 transactional fixtures disabled for that test) and asserts the invariant.355. **Verify, then stop.** Done when: RuboCop/Standard is clean, the suite is green, a new36 migration migrates and rolls back, and every AC has a test. Record the output with the37 `record-evidence` skill; the runner submits the work.3839## Commands4041- Gems are already installed; never run `bundle install`/`bundle update`/`bundle add`42 (installs need human approval; the hook does not catch these, the rule still holds). A43 missing gem goes in the evidence.44- Lint: `bundle exec rubocop` (or `bin/rubocop`, `bundle exec standardrb`).45- Tests: `bundle exec rspec` (one: `bundle exec rspec spec/x_spec.rb:42`) or `bin/rails46 test` (one: `bin/rails test test/x_test.rb:42`).47- Migrations: `bin/rails db:migrate` then `bin/rails db:rollback` and migrate again,48 only against the local development/test database; with none reachable, say so in the49 evidence.50- Security and types where configured: `bundle exec brakeman`, `bundle exec bundle-audit51 check`, `bundle exec srb tc` or `bundle exec steep check`.5253## Idioms that matter5455- **Small objects**: single-purpose classes and short methods; service objects for56 multi-step operations, query objects for complex reads, form objects for non-model57 input; no fat models or controllers, no concern that exists only to split a huge class.58- **Idiomatic Ruby** (Ruby Style Guide): `each`/`map`/`select` over `for`; guard clauses;59 keyword arguments for more than two parameters; `Data.define`/`Struct` for simple values;60 the `# frozen_string_literal: true` magic comment where the repo uses it; no61 monkey-patching core classes; no `method_missing`/`define_method` without precedent.62- **Rails the Rails way**: validations in the model and constraints in the database63 (`null: false`, unique indexes, foreign keys — the `add-db-migration` skill); scopes for64 reusable queries; strong parameters; `includes`/`preload` to kill N+1; `ActiveJob` for65 async work (the `background-jobs` skill); I18n for user-visible strings (the `i18n-l10n`66 skill).67- **Errors**: custom error classes under the app namespace; `rescue` specific classes;68 never `rescue Exception` (catches signals and exit) or `rescue nil`; re-raise with69 context; result objects for expected failures where the repo uses them.70- **Security by convention**: parameterised queries (`where(id: v)`, `where("x = ?", v)`),71 never interpolation; `html_safe`/`raw` only on sanitised content; `YAML.safe_load`, not72 `YAML.load`/`Marshal.load` on untrusted data; no `send`/`constantize` on user input.7374## Concurrency and resource safety7576- **Puma and Sidekiq run your code on many threads.** Class-level instance variables,77 `@@class_variables`, constants holding mutable objects and class-level `||=`78 memoisation are shared across requests and race. Use request-scoped objects,79 `ActiveSupport::CurrentAttributes`, or a `Mutex` held across the whole80 read-modify-write.81- **Lost updates on records**: read, change in Ruby, `save` loses concurrent writes. Use82 `record.with_lock { … }`, optimistic locking (`lock_version`, rescue83 `ActiveRecord::StaleObjectError`), or atomic SQL (`increment!`, `Model.update_counters`).84- **Check-then-create races**: `find_or_create_by` can insert duplicates; back it with a85 unique index and rescue `ActiveRecord::RecordNotUnique` (or `create_or_find_by`).86- **Jobs and transactions**: enqueue jobs and send mail in `after_commit` (or after the87 transaction), never inside it — the job can run before the row is visible or after a88 rollback. Jobs are retried: make them idempotent.89- **Files other requests read**: `File.write` is not atomic. Write to90 `Tempfile.create(["name", ".tmp"], File.dirname(target))` (unique, same filesystem), then91 `File.rename(tmp.path, target)`. Always use the block form of `File.open`. Cross-process92 exclusion uses `File#flock` or the database; a time-only lease lets a paused holder write93 late, so writes must check a version.94- **Timeouts**: set open/read timeouts on `Net::HTTP` and client gems; do not use95 `Timeout.timeout` around code that holds resources.9697## Review checklist — flag as defects9899Walk this against the diff. An item is grounds for CHANGES only when, in changed code, it100causes a concrete failure (wrong result, crash, lost or corrupted data, security hole) or101leaves an AC's own behaviour untested: cite the line and that failure. Otherwise it is an102`(optional)` note. Formatting the tools would fix, and preferences the repo103does not enforce, are not findings. Do not patch the code under review.104105- [ ] Bare `rescue`, `rescue Exception`, `rescue nil`, or a rescue that logs and continues106 where the caller needed the failure.107- [ ] Mutable class-level state or class-level memoisation shared across threads.108- [ ] A read-modify-write on a record without a lock, `lock_version` or atomic SQL; a109 `find_or_create_by` without a unique index.110- [ ] A job enqueued or mail sent inside a transaction; a non-idempotent retried job.111- [ ] An N+1 query in a loop or view the diff introduced.112- [ ] String-interpolated SQL; `html_safe`/`raw` on user content; `YAML.load`/`Marshal.load`113 /`constantize`/`send` on untrusted input; unpermitted params.114- [ ] A migration that is irreversible without `down`, changes data in a schema115 migration, or omits the constraint or index the model relies on.116- [ ] A shared file written in place or via a fixed temp name; `File.open` without a block;117 a time-only lock lease; an outbound call without timeouts.118- [ ] A new RuboCop disable or todo entry without a reason.119- [ ] An AC has no spec, or the spec stubs the behaviour the AC describes.120121## Capture lore122123This skill is one of the places durable, reusable knowledge naturally surfaces:124**While matching the repo you learn the service, query and form object patterns, the job adapter and the RuboCop exceptions.** That kind of fact is *lore*. Capture it via the **lore-capture125protocol in your brief** (`CLAUDE.factory.md`, step 11 "Memory contribution"):126call the Memory MCP `suggest_lore` once at the close of your work — reusable127conventions, gotchas, decisions, and boundaries only, never per-ticket trivia.