Building Rails applications efficiently: conventions, gems and habits that keep a team shipping
TL;DR
Difficulty: Intermediate
Rails conventions are a map every Rails developer already carries. Code on the map is free to read, code off it costs every future reader.
- Deviate deliberately and write it down in a decision log, or do not deviate.
- If a controller wants an eighth action, there is a noun you have not named yet.
- Scaffold what a manager edits, hand write what a customer touches.
- Check every gem against what Rails 7.1 already does, and treat gems that reach into the core as long term decisions.
- Put logic on the models, named after things in the business. Add a layer when the second case arrives, not when you can imagine it.
- Keep the test loop in seconds, pull requests small and unfinished work behind flags you remove again.
Two Rails teams with the same framework and equally good developers can end up a year apart: one ships something small every day, the other fights its own codebase. The difference is a few dozen small habits. Here they are, worked through on the first month of a bicycle workshop chain's booking and repair application, with one feature built two ways and the lines counted.
The question behind this article
Two Rails teams can start in the same month, with the same framework, the same database and developers of the same calibre. A year later one of them ships something small almost every day, and the other spends its Mondays working out why last week's change broke the invoices. The difference is rarely talent. It is a few dozen small choices about where code goes, which libraries come in, how big a change is allowed to get and how long anyone waits to find out whether it works.
This article is about those choices, as of Rails 7.1 in March 2024. It assumes you know how a Rails application is laid out (the chapter on how a Rails application is structured covers that) and how models and queries work (see Active Record done well).
I keep using the invented example from this series. Freewheel Cycles is a chain of six bicycle repair workshops in Limerick (freewheelcycles.example), run by its founder Niamh, with 38 mechanics, about 1,150 repair bookings a week and 9,000 active customers. Two developers are building its own web application to replace the spreadsheets and a rented booking widget: Aisling, who has four years of Python, and Cian, who has three years of TypeScript and React. Neither had written Ruby before. In the decision method chapter they chose Rails, by a close margin, for a small team, an integrated stack and a live workshop board without a separate React application. They have six months for the first version. This article is their first month.
Conventions are a map everyone already carries
The most useful way I know to think about Rails conventions is this: they are a map that every Rails developer already carries in their head. A Booking model lives in app/models/booking.rb, its table is bookings, its controller is BookingsController, its views sit in app/views/bookings, and POST /bookings creates one. Nobody has to write that down for your project, because it is written down for every Rails project at once.
That gives every piece of code you write one of two prices.
- Code on the map is free to read. A developer who has never seen your application can predict where it lives and what it does before opening the file.
- Code off the map has a running cost. Someone has to explain it, document it, defend it in review and teach it to the next person. Every future reader pays a little, every time.
David Heinemeier Hansson, who created Rails, makes the same argument in the Rails Doctrine: conventions spare you a jungle of decisions that only need making once, and he warns that "the cost of going off the Rails is under appreciated"1. He also says most applications have a small unique part that genuinely needs its own shape. The skill is telling the two apart.
So here is the rule I would give any small Rails team: deviate deliberately, write it down, or do not deviate. Every departure from convention gets one entry in a decision log in the repository, two or three sentences on why. If you cannot write those sentences, the deviation is a habit from another framework, not a decision. I call that log the deviation ledger, and a short ledger is one of the best signs of a healthy Rails codebase.
Example: where does "mark a bike ready" live?
At Freewheel, a mechanic finishes a repair and taps "mark ready". The job card moves to "ready" and the customer gets the "your bike is ready" message from the background jobs chapter.
Here is the test I run on any codebase. Ask a Rails developer who has never seen the project where this feature lives, and see if they can guess. In Freewheel's application, built on the map, the answer is predictable:
- the route:
config/routes.rb, areadinessresource nested underjob_cards - the controller:
app/controllers/job_cards/readinesses_controller.rb, actioncreate - the rule: a
mark_ready!method inapp/models/job_card.rb - the test:
test/controllers/job_cards/readinesses_controller_test.rb
Four guesses, four hits. In a codebase that has drifted off the map, the same feature might live in a JobCardsController#mark_ready action calling app/services/job_cards/mark_ready_service.rb, which talks to app/repositories/job_card_repository.rb and app/notifiers/customer_notifier.rb. None of that is wrong code. But a newcomer cannot guess a single file, and every one of those folders is a convention the team invented and now has to teach. You will see both versions in full further down, with the lines counted.
Everything is a resource: the seven actions and the eighth action test
Rails routing is built on resources. One line, resources :bookings, creates seven routes that map to seven controller actions: index, show, new, create, edit, update and destroy2. Those seven cover create, read, update and delete (CRUD) for one kind of thing over HTTP. The routing guide is open about the fact that you can add more actions, with member and collection routes2. You can. The question is whether you should.
37signals, the company behind Basecamp and Rails, answered that question years ago. In a 2015 episode of the Full Stack Radio podcast, David Heinemeier Hansson described how Basecamp 3 ended up with 179 controllers3. His heuristic, as transcribed by Jerome Dalbert in 2016: whenever he wants to add an action that is not one of the default ones, he makes a new controller instead, often namespaced under the original4. An "inbox, but only the pending ones" becomes Inboxes::PendingsController#index, not InboxesController#pendings.
That is an opinion, and it is one person's, but I find it holds up. I turn it into a small rule I call the eighth action test: if a controller wants an eighth action, there is a noun you have not named yet. Find the noun, give it its own controller with some of the seven actions, and the code goes back on the map.
Why this helps a team ship:
- Each controller stays short, with its own
before_actionfilters that apply to every action in it, instead of a growing list ofonly:andexcept:conditions. - The route file reads like a list of things in the business.
- Each new controller has an obvious test file, and the tests stay small.
Example: three requests that look like custom actions
Here are three things Niamh asked for in the first weeks, first as the tempting custom action, then with the missing noun named.
| Niamh's words | Tempting custom action | The missing noun | Conventional route |
|---|---|---|---|
| "Mark the bike ready" | JobCardsController#mark_ready | a readiness | POST /job_cards/:job_card_id/readiness to JobCards::ReadinessesController#create |
| "Show me only today's bookings" | BookingsController#today | none: it is a filter on the list | GET /bookings?on=2024-03-05 to BookingsController#index |
| "Let a customer cancel" | BookingsController#cancel | a cancellation | POST /bookings/:booking_id/cancellation to Bookings::CancellationsController#create |
The second row shows the limit of the rule. Jerome Dalbert, who uses the approach himself, points out that a plain query parameter is often enough for a simple filter4. Fair play to him, he is right. A list of today's bookings is still the list of bookings. A new controller earns its place when the filtered screen has its own rules, its own layout or its own permissions, and a date in the URL has none of those.
Here is the route for the first row, which you will see working later:
# config/routes.rb
resources :job_cards, only: %i[index show] do
scope module: :job_cards do
# POST /job_cards/:job_card_id/readiness -> JobCards::ReadinessesController#create
resource :readiness, only: :create
end
end
resource (singular) is right here because a job card has exactly one readiness, so the URL needs no id of its own. scope module: :job_cards puts the controller in the JobCards namespace, in the folder app/controllers/job_cards/.
Vertical slices: the shape of a day's work
A vertical slice is one small feature built through every layer at once: route, controller, model, migration, view, test, and a deploy. The opposite is building in horizontal layers: all the models in week one, all the controllers in week two, the screens in week three. Horizontal work looks efficient on a plan. In practice nothing can be tried by the person paying until the very end, and every mistake in the models surfaces in week three.
Rails is unusually good at vertical slices because the layers already know about each other by convention. Adding one resource touches a handful of files you can name in advance. That is the habit the fastest Rails teams share: they finish something Niamh can click almost every day.
Here is the slice as a flow, with the eighth action test built in:
I write the test first, as you can see in the second box. That is how I work on every Rails application I build, and the testing series later in this programme walks through it step by step. For this article it is enough that the test exists before the slice is called done.
Example: Freewheel's first month as a plan of slices
Aisling and Cian planned their first four weeks as eight slices, two a week, each one finished, tested and on the staging server by Friday. The Rails pieces column links each slice to the chapter that explains it.
| Week | Slice | Rails pieces | What Niamh can try on Friday |
|---|---|---|---|
| 1 | Back office for workshops, mechanics and parts | trimmed scaffold, seeds | edit the six workshops, the 38 mechanics and the parts list |
| 1 | Book a time slot with one mechanic | BookingsController, overlap validation and a database constraint (Active Record chapter) | book a slot as a customer on staging |
| 2 | A job card for every booking, the board read only | JobCard with status, JobCardsController#index grouped by status | see Saturday's cards in three columns |
| 2 | Move a card on the board, live for everyone | Turbo Stream broadcast (Hotwire chapter) | drag a card on one laptop, watch it move on another |
| 3 | Mark ready and tell the customer | JobCards::ReadinessesController, a background job and a mailer | receive the "your bike is ready" email |
| 3 | Before and after photos on a job card | Active Storage (background jobs, email and files) | upload two photos from a phone |
| 4 | Parts used on a job card, in one workshop only | PartUsage nested under job cards, a feature flag | record parts on real jobs in one workshop |
| 4 | Nightly reorder report | a scheduled job and a mailer | receive the report on Saturday morning |
Two things are deliberately missing: invoices with VAT and reporting. They depend on the parts data being right, so they wait until month two, when a month of real job cards exists to test them against.
Generators: scaffold what a manager edits, hand write what a customer touches
Rails generators create files from templates. bin/rails generate model creates a model, a migration, a test and a fixture file. bin/rails generate scaffold goes all the way: the Rails 7.1 generators guide shows a single scaffold creating a migration, a model, a controller with all seven actions, six view templates, two JSON templates, a helper, fixtures, a model test, a controller test and a system test, plus the route5. That is 16 files and a folder from one command.
That is a gift and a trap. Scaffolds are excellent for screens that really are tables of records that staff edit: workshops, mechanics, parts. They are poor for anything a customer touches, because a customer facing flow is never "a form for every column". A booking page has a slot picker, a confirmation and a message, not a text field for mechanic_id.
My rule for teams: scaffold what a manager edits, hand write what a customer touches, and delete what you do not use on the same day. A generated file nobody uses is still a file the next reader has to open to find out it does nothing.
You can also tell the generators what not to create. Rails documents the config.generators block for this6.
Example: trimming the generators, then scaffolding the parts list
Freewheel has no JSON API yet (the mechanics app comes later) and keeps view logic in partials rather than helper modules. So in week one Aisling turned two generators off:
# config/application.rb, inside class Application
config.generators do |g|
g.helper false # no empty app/helpers/*_helper.rb per resource
g.jbuilder false # no JSON views until the mechanics app needs an API
end
helper is a documented Rails option6. jbuilder is an option the jbuilder gem adds to the scaffold generator, and jbuilder is in the default Rails 7.1 Gemfile, which is why scaffolds create JSON templates in the first place.
Then the back office for parts, which really is a table that managers edit:
bin/rails generate scaffold Part name:string sku:string:uniq stock_quantity:integer reorder_level:integer
bin/rails db:migrate
The :uniq after sku adds a unique index to the migration. Before committing, Cian added null: false and a default to the stock columns in the migration (the Active Record chapter explains why constraints belong in the database too), read every generated file once, and deleted the destroy action and its button: parts that have been used on a job are never deleted, only marked as discontinued. The scaffold saved an afternoon. Reading it took twenty minutes. Fair trade, both of them.
The booking page, by contrast, Aisling wrote by hand with bin/rails generate controller Bookings new create, which creates only the controller, two views and a test.
Choosing gems: does Rails already do this?
A gem is a packaged Ruby library. The Gemfile lists the gems your application uses, and Bundler installs them. Gems are one of the reasons Rails teams are fast, and also one of the commonest reasons a Rails application becomes hard to upgrade. Every gem is code you did not write, cannot fully read, and must keep compatible with every future version of Rails and Ruby. The chapter on five years of upgrades and maintenance puts numbers on that cost.
So the first question about any gem is whether Rails already does the job. Rails has absorbed many jobs that used to need gems. Paperclip, once the standard way to attach files, was deprecated by its maintainers at thoughtbot in May 2018, with Rails' own Active Storage recommended for new projects7. Rails 7.1 added normalizes to Active Record, which cleans up values such as email addresses before they are saved8, a job that small gems used to do.
Here is the checklist Freewheel uses before any gem goes into the Gemfile. Each question has the place to find the answer.
| Question | Where to look | A good answer |
|---|---|---|
| Does Rails 7.1 already do this? | the Rails Guides and the 7.1 release notes | no, or not well enough for this case |
| Is it maintained? | release history on rubygems.org, recent commits, how issues get answered | releases within the last year, or a stable gem that simply needs none |
| Does it support our Rails and Ruby versions? | the gemspec's dependencies, the changelog | Rails 7.1 and Ruby 3.3 named or tested |
| Who maintains it? | the repository, the maintainers list | a company that depends on it, or several active people |
| What does the licence allow? | the LICENSE file, rubygems.org | a licence that permits how the application uses it |
| How widely is it used? | download counts on rubygems.org, other projects using it | widely used, so problems are found by others first |
| How deep does it reach? | does it add model macros, patch Rails, own a table? | it sits at the edge and can be removed in a day |
Root gems and leaf gems
The last question in that table matters most, and it is the one checklists usually skip. I sort gems by their exit cost: how much code you would have to change to remove them.
- Leaf gems sit at the edge. A pagination gem touches a few controllers and views. A profiler touches nothing in production. If one dies, you replace it in a day.
- Root gems grow into the middle of your application. An authentication gem shapes your user model, your routes and your sessions. A state machine gem shapes every model that has a status. An admin framework owns whole screens. Replacing one is a project.
Add leaf gems freely after the checklist. Add a root gem only with an entry in the deviation ledger, because it is a decision the team will live with for years.
The licence question deserves a second look too, because licences differ in what they allow. Most Rails gems use the MIT licence, which permits almost anything. Sidekiq's open source edition is licensed under the GNU Lesser General Public License version 3 (LGPL)9, which is fine for using it as a library in your application. Brakeman, the security scanner, uses its own Brakeman Public Use License, which explicitly allows using it to analyse your own software, and requires a paid licence for commercial uses such as offering scanning as a service10. A team scanning its own code is fine. A company selling code scanning is not. That is exactly the kind of thing the checklist is for.
Example: four gems Freewheel considered in month one
| Need | Rails 7.1 already has | Decision | Leaf or root |
|---|---|---|---|
| Trim and lowercase customer emails | normalizes | no gem | not applicable |
| Paginate the bookings list for managers | nothing built in | Pagy | leaf |
| Show parts usage to one workshop first | nothing built in | Flipper | leaf, if flags are removed after use |
| Track job card status changes with rules | enum plus a model method | no gem for now, a ledger entry to revisit | would be root |
The last row is the interesting one. Cian, coming from TypeScript, wanted a state machine library for job card statuses. The team wrote down why not yet: four statuses and three transitions fit in one model method each, and a state machine gem would shape every future status column. If the rules grow, the ledger entry says when to look again.
A short list of well kept gems, as of March 2024
These are widely used, actively maintained gems for common needs, with the latest version on rubygems.org on 5 March 202411. It is a starting point for your own checklist, not an endorsement of one over another.
| Need | Widely used gems (version on 5 March 2024) | Note |
|---|---|---|
| Authentication | Devise 4.9.3 | a root gem; the chapter on authentication and security compares it with building on has_secure_password |
| Authorisation | Pundit 2.3.1, Action Policy 0.6.8 | plain Ruby policy objects |
| Background jobs | Sidekiq 7.2.2 (Redis), GoodJob 3.26.1 (PostgreSQL) | Solid Queue from 37signals first appeared in December 2023 and is still at version 0.2 |
| Pagination | Pagy 7.0.9, Kaminari 1.2.2 | Kaminari's last release was in December 2021 and it remains widely used, which shows a quiet gem is not necessarily a dead one |
| Feature flags | Flipper 1.2.2 | storage adapters include Active Record |
| Test data | factory_bot_rails 6.4.3 | an alternative to Rails fixtures |
| Finding slow pages and N+1 queries | rack-mini-profiler 3.3.1, Bullet 7.1.6 | rack-mini-profiler is already in the default Gemfile, commented out |
| Security checks | Brakeman 6.1.2, bundler-audit 0.9.1 | static analysis of your code, and known vulnerabilities in your gems |
| Code style | RuboCop 1.61.0 with rubocop-rails 2.24.0, or Standard 1.34.0 | see the code style section below |
| Safer migrations | strong_migrations 1.7.0 | catches migrations that would lock a busy table |
Where does the business logic go? Concerns, service objects and plain Ruby objects
This is the longest running argument in the Rails community, and both sides have serious people on them. It matters for speed because it decides how many places a developer has to look to understand one feature.
Some terms first. A concern is a Ruby module that uses ActiveSupport::Concern to bundle methods, associations, validations and callbacks into one named slice that a model (or controller) includes. The Rails getting started guide introduces them as a way to make large models easier to understand and to share behaviour12. A service object is a class whose job is to perform one operation, usually with a single public method like call. A plain old Ruby object (PORO) is any ordinary Ruby class that does not inherit from Active Record.
The case for rich models and concerns
David Heinemeier Hansson wrote in 2012 that Basecamp had almost forty concerns, with names such as Trashable, Searchable and Taggable, each holding the data access and the domain logic for one slice of responsibility13. Ten years later, Jorge Manrubia of 37signals described how they still organise code: domain models, both Active Record classes and POROs, exposing methods that controllers and jobs call directly, and no default layer of services, commands or interactors on top14. In a companion post he explains their convention of putting a concern used by only one model in a folder named after that model, app/models/recording/completable.rb for example15.
The argument underneath is older than Rails. Martin Fowler named the anaemic domain model as an anti pattern in 2003: objects named after the business that hold data but no behaviour, with all the logic in service classes on top, which he calls a procedural design in object clothing16.
The case for service objects
Bryan Helmkamp of Code Climate made the opposite case in a widely read 2012 post. He argued that fat models usually break the single responsibility principle, that extracting concerns from one model is like tidying a room by sweeping the clutter into drawers, and that some operations deserve their own object: those that are complex, reach across several models, or talk to an external service17. Many Rails teams have followed that advice since, and an app/services folder is common in Rails codebases.
The benefits are real. A list of service classes is an index of everything the application does. Each operation has one obvious entry point. Developers coming from other ecosystems, where a separate service layer is normal, often find this shape familiar.
My view
My view: start with the model, and name things after the business.
- Default: a method on the model the operation is about.
job_card.mark_ready!,booking.cancel!. The controller calls it, the test calls it. - When a model grows a cohesive trait (several methods, a scope and a validation that belong together), extract a concern in a folder named after the model, as 37signals do. It is still the model, just in two files.
- When an operation spans several models or an outside service, make a plain Ruby class in
app/models, named after the thing in the business, not after the act of doing it.Invoice::IssuanceorReorderReport, notCreateInvoiceService. - Avoid a default
app/servicesfolder. Not because service objects are wrong, but because a folder named after a technical pattern becomes the place everything goes, and it moves code off the map.
The test I use is simple: would Niamh recognise the name? Readiness, cancellation, reorder report, invoice: those are things in her workshop. Service, manager, handler, processor: those are things only developers see. When a class name only makes sense to developers, it is usually a sign the code has not yet found its place in the business.
Example: the invoice as a plain Ruby object
In month two, Freewheel needs invoices: labour at €52 an hour, the parts used, and VAT at 23%, the Irish standard rate18, with sequential invoice numbers. That touches a job card, its part usages, the customer and a numbering sequence. It is a genuine multi model operation, so it gets its own class, named after the business event:
# app/models/invoice/issuance.rb
# Issues the invoice for a finished job card. Named after the business event.
class Invoice::Issuance
def initialize(job_card)
@job_card = job_card
end
def issue!
# the next number and the invoice are saved together, or not at all
Invoice.transaction do
Invoice.create!(
job_card: @job_card,
number: Invoice.next_number,
labour_cents: @job_card.labour_cents,
parts_cents: @job_card.part_usages.sum(:price_cents),
vat_rate: Invoice::IE_STANDARD_VAT_RATE # 0.23
)
end
end
end
It lives in app/models, Zeitwerk loads it from the file name like any model, and the controller that uses it is JobCards::InvoicesController#create. The calculation itself, and the tests that pin it down, belong to the testing series later in this programme. What matters here is the shape: one class, one business name, on the map.
One feature built twice: the conventional way and the layered way
Talk about architecture is easy to start and hard to settle. So here is one feature, mark a bike ready, built twice, with identical behaviour: the card moves to "ready", the customer's notification job is queued once, marking it ready again sends nothing, and the mechanic is sent back to the card. Both versions run on Rails 7.1, and both test suites pass.
The conventional way
The route you saw earlier, then a controller with one action:
# app/controllers/job_cards/readinesses_controller.rb
class JobCards::ReadinessesController < ApplicationController
before_action :set_job_card
def create
@job_card.mark_ready!
redirect_to @job_card, notice: "Marked ready. The customer has been told."
end
private
def set_job_card
@job_card = JobCard.find(params[:job_card_id])
end
end
The rule lives in the model, next to the status it changes:
# app/models/job_card.rb (the enum comes from the Active Record chapter)
class JobCard < ApplicationRecord
enum :status, { waiting: 0, in_repair: 1, ready: 2, collected: 3 }
# Moves the card to "ready" and tells the customer, once.
def mark_ready!
return if ready?
update!(status: :ready)
BikeReadyJob.perform_later(self)
end
end
update! saves and commits before the job is queued, so the job never looks for a card that was rolled back. The background jobs chapter explains why the order matters, and builds BikeReadyJob.
One line in the job card view:
<%# app/views/job_cards/show.html.erb %>
<%= button_to "Mark ready", job_card_readiness_path(@job_card) unless @job_card.ready? %>
button_to renders a small form that sends a POST, which is what the create route expects. Then the tests: one request test that goes through the route, and one model test for the rule that matters most to customers, never notifying twice.
# test/controllers/job_cards/readinesses_controller_test.rb
require "test_helper"
class JobCards::ReadinessesControllerTest < ActionDispatch::IntegrationTest
test "marking a card ready tells the customer" do
job_card = job_cards(:gravel_bike_in_repair)
assert_enqueued_with(job: BikeReadyJob, args: [job_card]) do
post job_card_readiness_path(job_card)
end
assert job_card.reload.ready?
assert_redirected_to job_card_path(job_card)
end
end
# test/models/job_card_test.rb, inside class JobCardTest
test "a card that is already ready does not tell the customer again" do
job_card = job_cards(:city_bike_ready)
assert_no_enqueued_jobs { job_card.mark_ready! }
end
The two fixtures sit in test/fixtures/job_cards.yml, each pointing at a booking fixture:
gravel_bike_in_repair:
booking: gravel_bike_service
status: in_repair
city_bike_ready:
booking: city_bike_puncture
status: ready
Authentication and the question of which mechanic may mark which card are left out here on purpose. They belong to the chapter on authentication, authorisation and security.
The layered way
Now the same behaviour as it often arrives from a team that learned a layered style elsewhere. A custom member action:
# config/routes.rb
resources :job_cards, only: %i[index show] do
member do
patch :mark_ready
end
end
# app/controllers/job_cards_controller.rb, a new action
def mark_ready
result = JobCards::MarkReadyService.new(
job_card_id: params[:id],
repository: JobCardRepository.new,
notifier: CustomerNotifier.new
).call
if result.success?
redirect_to job_card_path(result.value), notice: "Marked ready. The customer has been told."
else
redirect_to job_card_path(params[:id]), alert: result.error
end
end
A service with injected collaborators:
# app/services/job_cards/mark_ready_service.rb
module JobCards
class MarkReadyService
def initialize(job_card_id:, repository:, notifier:)
@job_card_id = job_card_id
@repository = repository
@notifier = notifier
end
def call
job_card = @repository.find(@job_card_id)
return Result.success(job_card) if job_card.ready?
job_card.status = "ready"
@repository.save!(job_card)
@notifier.bike_ready(job_card)
Result.success(job_card)
rescue ActiveRecord::RecordInvalid => error
Result.failure(error.message)
end
end
end
And the three small classes it needs:
# app/services/result.rb
class Result
attr_reader :value, :error
def self.success(value) = new(value: value)
def self.failure(error) = new(error: error)
def initialize(value: nil, error: nil)
@value = value
@error = error
end
def success? = error.nil?
end
# app/repositories/job_card_repository.rb
class JobCardRepository
def find(id) = JobCard.find(id)
def save!(job_card)
job_card.save!
job_card
end
end
# app/notifiers/customer_notifier.rb
class CustomerNotifier
def bike_ready(job_card)
BikeReadyJob.perform_later(job_card)
end
end
The view's button changes to button_to "Mark ready", mark_ready_job_card_path(@job_card), method: :patch. The service gets a unit test with mock objects standing in for the repository and the notifier, 29 lines for the two cases, and the controller gets a request test much like the conventional one.
What the count says
Here is the count. It covers the non blank lines each version adds (for the model, only the new method, and never the comment naming the file), including the fixtures and the two tests described but not printed, and the files each version touches.
The layered version needs 102 lines where the conventional one needs 44, more than twice the code for identical behaviour. It also adds three new folders to the application, app/services, app/repositories and app/notifiers, each a convention every future developer must learn. And there is a quieter cost in the tests: the mock based service test checks that the service calls find, save! and bike_ready in the right order. It would still pass if a database constraint made save! fail in real life, because the mock repository never touches the database. The conventional request test runs the real route, the real model and the real database.
To be fair to the layered style: none of its classes are badly written, and the repository and notifier make the service testable without a database. In a large system with several ways of storing job cards, that indirection could pay for itself. Freewheel has one database and one way of storing job cards. The indirection protects against a change that is not coming, and it is paid for on every read.
That is my rule of thumb for this whole debate: add a layer when the second case arrives, not when you can imagine it.
Code style: pick a rule book once, then stop arguing
Code style arguments are the most expensive conversations a small team can have, because they never end and they decide nothing about the product. The fix is to hand the rule book to a tool.
RuboCop is the standard Ruby linter and formatter: it checks code against a set of rules ("cops") and can correct many of them automatically. rubocop-rails adds Rails specific cops. In March 2024 a team has three reasonable starting points:
- RuboCop with
rubocop-railsand its default configuration, adjusted over time. - Standard, from Test Double, a fixed RuboCop configuration you are not meant to argue with.
rubocop-rails-omakase, a gem David Heinemeier Hansson released on 29 December 2023 with his own house style for Rails19. Its README describes the rules as one person's aesthetic sensibilities, a starting point rather than right or wrong. It is a separate gem you add yourself, not part ofrails newin Rails 7.1.
My view: pick one in week one, run it automatically, and never discuss style in a code review again. Which one matters much less than having one.
Example: the RuboCop setup at Freewheel
Aisling and Cian chose the omakase rules because they had no Ruby habits of their own to protect:
# Gemfile
group :development do
gem "rubocop-rails-omakase", require: false
end
# .rubocop.yml
# Omakase Ruby styling for Rails
inherit_gem: { rubocop-rails-omakase: rubocop.yml }
# Our own rules go here, each with a reason in docs/decisions.
bundle exec rubocop # check everything
bundle exec rubocop -a # fix what can be fixed safely
The comment in the YAML is the deviation ledger again: any rule they switch off gets a line of reasoning. In the first month they switched off none.
Fast feedback: seconds, not minutes
A developer's day is a long series of small loops: change something, find out whether it worked, change again. The length of that loop decides how fast a team is, more than typing speed or experience. Rails 7.1 gives you several short loops out of the box. Most teams only use some of them.
bin/devstarts the Rails server together with the CSS and JavaScript watchers, using foreman and aProcfile.dev. Rails creates it when you choosetailwindcss-rails,cssbundling-railsorjsbundling-rails20. One command, everything reloads.bin/rails console --sandboxopens the console in a transaction that is rolled back when you exit, so you can try a model method on real development data without changing it21.- The
debuggem has been in the default Gemfile since Rails 7. Putdebugger(orbinding.break) in any line of code, and the server or the test stops there with a prompt where you can inspect variables and step through22. - The development log in
log/development.logshows every request, every SQL query with the line of code that caused it (verbose query logs are switched on in the default development configuration) and, new in Rails 7.1, where each background job was enqueued. - One test at a time.
bin/rails test test/models/job_card_test.rb:27runs the test on line 27.bin/rails test test/modelsruns a folder.--fail-faststops at the first failure23.
The maths of waiting
The cost of a slow loop is easy to underestimate because each wait is short, so multiply it out. Both formulas below are plain rates multiplied together, explained in Foundations: ratios and rates. The waiting time per developer per day is
where is the waiting time per developer per day, is the number of test runs in a day and is the time one run takes. Over a month for a whole team it becomes
where is the team's waiting time per month, is the number of working days in the month and is the number of developers. It is the same idea scaled up, a daily rate times days times people (Foundations: ratios and rates).
Example: Freewheel's test loop
The numbers in this example are illustrative, chosen to be typical for a young application, and labelled as such. By the end of month one, Freewheel's suite has a few hundred tests and takes 45 seconds. A developer working test first runs tests about 60 times a day. Running the whole suite every time:
That is runs at seconds each. Running only the file they are working on, at about 3 seconds, and the full suite before each push:
The same runs, now at seconds. Over a month of 20 working days, for two developers, the full suite habit adds up to
with minutes, days and developers, against 2 hours for the single file habit. The difference is 28 hours a month, three and a half working days, out of a six month budget. Nobody would sign off three and a half days a month of staring at a terminal, but that is what the habit costs if no one names it.
The full suite still runs, before every push and in continuous integration (CI). The final chapter of the testing series is about keeping that run fast as the suite grows.
Small pull requests, trunk based development and feature flags
A pull request (PR) is a proposed change that someone reviews before it joins the main branch. Its size decides how well it gets reviewed. Google's engineering practices guide says there is no hard rule, but that about 100 lines is usually a reasonable size for a change and 1,000 lines is usually too large24. Large changes get skimmed, small ones get read.
Small PRs only work if they can be merged before the feature is finished. That is what trunk based development is: everyone integrates into one main branch (the trunk) at least daily, and any branch lives a couple of days at most. Paul Hammant, who maintains the main reference on the practice, puts the limit for short lived feature branches at about two days25. The research behind the book Accelerate by Nicole Forsgren, Jez Humble and Gene Kim (2018) found trunk based development among the technical practices that predict higher software delivery performance26.
The piece that makes this possible is a feature flag: a switch in the running application that hides unfinished work. Pete Hodgson's article on feature toggles separates them by purpose: release toggles hide unfinished features, experiment toggles run A/B tests, ops toggles switch off expensive features under load, permission toggles open features to some users27. He also warns that toggles carry a cost and that release toggles should be short lived. In Rails, Flipper is a widely used gem for this, and it can store flags in your own database through Active Record28.
Example: parts usage behind a flag in one workshop
Recording parts on job cards (week four of the plan) changes how mechanics work, and the Saturday peak is the worst time to discover a problem: 30% of Freewheel's online bookings arrive between Friday 6pm and Saturday noon. So Cian merged the feature in three small PRs over two days, hidden behind a flag, and switched it on for one workshop on a Tuesday.
bundle add flipper flipper-active_record
bin/rails generate flipper:setup
bin/rails db:migrate
In the job card view, the parts section only appears where the flag is on. Flipper includes an identifier in every Active Record model, so a workshop can be the "actor" the flag checks:
<%# app/views/job_cards/show.html.erb %>
<% if Flipper.enabled?(:parts_on_job_cards, @job_card.workshop) %>
<%= render "job_cards/part_usages", job_card: @job_card %>
<% end %>
And in the console, on the Tuesday:
# one workshop first
Flipper.enable_actor(:parts_on_job_cards, Workshop.find_by!(name: "Castletroy"))
# two weeks later, everyone
Flipper.enable(:parts_on_job_cards)
The last step is the one teams forget. Once all six workshops use it, the if comes out of the view, the flag is deleted, and the PR that removes it is the smallest of all. A release toggle that stays for months is no longer a toggle, it is a second version of your application that nobody tests.
Developer documentation that lives in the repository
Documentation that lives in a wiki drifts away from the code within weeks. Documentation in the repository changes in the same pull request as the code it describes, and gets reviewed with it. Rails gives you one piece of this for free: bin/setup, generated by rails new, installs gems and prepares the database in one command, and is meant to be safe to run again at any time.
Three files cover most of what a small team needs:
README.md: what the application is, and how to get from a fresh laptop to a running app in three commands.docs/decisions/: architecture decision records (ADRs), the format Michael Nygard proposed in 2011. Each is a short file with a title, the context, the decision and its consequences, numbered and never deleted, only superseded29. This is where the deviation ledger lives.bin/setupandbin/dev: kept working, so the README can stay short.
Example: Freewheel's README and its first decision records
# Freewheel Cycles
Booking, workshop board, job cards and parts for six workshops.
## Run it
bin/setup # gems, database, seeds
bin/dev # server and CSS watcher on http://localhost:3000
bin/rails test
## Where things live
Standard Rails. Anything that is not is listed in docs/decisions.
# 0003. No state machine gem for job card status (yet)
Status: accepted, March 2024
Context: Job cards have four statuses and three transitions.
Decision: Use a Rails enum and one model method per transition.
Consequences: Revisit when a status gains a second way in or
a transition needs its own permissions.
Its first ten decision records took less than an hour to write in total, and they answer the question every new developer asks in week one: why is it like this?
For the person paying for this
If you commission a Rails application, you do not need to read the code to judge whether the team works this way. Ask five questions, and ask to see the answer rather than hear it.
- What can I click this Friday? A team working in vertical slices always has an answer. A team building in layers says "in a few weeks".
- Show me the decision log. A short list of deliberate deviations, each with a reason, is a good sign. No list at all, or a codebase full of patterns nobody wrote down, is not.
- How big was the last pull request? A few hundred lines is healthy. Several thousand means changes are piling up unreviewed.
- How long does the test suite take, and does it run on every change? Minutes, and yes.
- How long would a new Rails developer need to run the application? With a working
bin/setup, the answer is under an hour.
Those answers tell you more about your next twelve months than any architecture diagram. If you want to put them to a team, or to me, the free workshop is a good place to start. I publish my prices so you can compare like with like, and when I build a web application for you, the code, the accounts and the data are yours.
Conclusion
The Rails teams that ship every day are not doing anything exotic. They keep their code on the map that every Rails developer already carries: resources with seven actions or fewer, logic on the models named after the business, generators trimmed to what they use. Every departure is deliberate and written down. They choose gems with a checklist and treat the ones that reach into the core of the application as long term decisions. They keep their loops short, their pull requests small and their unfinished work behind flags that they remove again.
None of that is a rule from the framework. It is a set of habits that lets the framework's conventions do the work. Aisling and Cian's first month at Freewheel is eight slices, each one finished, tested and in front of Niamh by Friday. The next chapter in this series is about authentication, authorisation and security, and the one after it about keeping all of this tidy when the application is two years old and three times the size.
