When does CurrentAttributes turn into hidden global state in a Rails codebase, and which values should you pass as explicit parameters instead?
answer
- the Current docs warn: a few top-level globals
- nil in console, rake, jobs and seeds
- models that read Current hide a dependency
- edges set it, domain methods take arguments
- audit defaults are the honest use
basics
~20 sCurrent becomes hidden global state when domain logic reads it to decide behaviour: the dependency is invisible and breaks in consoles, rake tasks and jobs. Keep it for account, user and request details in audit defaults; pass decision inputs as arguments.
solid answer
~50 sRails' own documentation for `CurrentAttributes` warns that it is easy to overdo: it should hold a few top-level values, account, user and request details, used by nearly every action, not controller-specific data. It becomes hidden global state when models, policies or services read `Current` to make decisions: `Contact#visible?` checking `Current.user`, a `default_scope` keyed on `Current.account`, a validation that consults `Current`. Those methods now have an input you cannot see in their signature, they return different answers depending on who called them, and they fail or silently widen in a console, a rake task, a seed file or a job, where nothing set `Current`. A sound split: the controller sets `Current` at the edge; `Current` feeds cross-cutting defaults such as `belongs_to :creator, default: -> { Current.user }` and audit fields; domain methods take `account:` and `user:` explicitly, so they can be called and tested from anywhere.
go deeper
Recall that Current holds only a few per-request values like account and user, and that it is empty outside a request.
Explain which uses are safe, audit defaults and request ids, and why model methods that decide behaviour from Current break in console, jobs and rake tasks.
Refactor hidden dependencies into explicit parameters, avoid tenant default scopes keyed on Current, and use the console-empty test in reviews.
Own the codebase rule for ambient context versus explicit arguments, weighing boilerplate against hidden coupling, and enforce it in review.
## The trade-off in one sentence `Current` makes per-request values available everywhere without passing them, and that is both its value and its cost: any code can depend on it, and nothing in a method's signature shows that it does. ## Rails' own warning The documentation in `ActiveSupport::CurrentAttributes` is unusually direct. It says it is easy to overdo a global singleton like `Current` and tangle your model; that `Current` should be used only for a few top-level globals such as account, user and request details; that those attributes should be used by more or less all actions on all requests; and that putting controller-specific attributes in it creates a mess. That is a good checklist for review. ## Signs `Current` has become hidden state In a multi-tenant CRM, watch for these: - **Decisions in models depend on it.** `Deal#editable?` returns `Current.user.manager? || owner == Current.user`. The method looks like a pure question about a deal but answers differently per caller. - **Tenant scoping hangs on it.** `default_scope { where(account: Current.account) }` scopes every query automatically, until code runs where `Current.account` is `nil`, at which point the scope matches rows with no account instead of the tenant's. - **It carries request-specific data.** `Current.filter_params`, `Current.selected_pipeline`: data one controller needs, stored where every class can reach it. - **Tests need elaborate setup.** Every model test sets three `Current` values before anything works, which shows how many methods silently depend on them. Each of these breaks the same way: code runs **outside a request** (`bin/rails console`, a rake task, `db/seeds.rb`, a job, a data migration) and `Current` holds only defaults. ## The healthy shape A useful rule is **set at the edge, read for defaults, pass to the domain**: 1. **Edges set it.** `ApplicationController` sets `Current.account` and `Current.user`; a job sets them from its arguments with `Current.set`. 2. **Cross-cutting defaults read it.** Audit columns, `belongs_to :creator, default: -> { Current.user }`, log tags and request ids. These are the same for every action and harmless to omit in a console, where a default can be supplied explicitly. 3. **Domain operations take arguments.** Permission checks, pricing, tenant-specific queries: ```ruby class Deal < ApplicationRecord def editable_by?(user) user.manager? || owner == user end end class DealsController < ApplicationController def update deal = Current.account.deals.find(params[:id]) head :forbidden and return unless deal.editable_by?(Current.user) # ... end end ``` `editable_by?(user)` can be called from a job, a console or a test with any user. The controller is the one place that reads `Current` to supply it. ## Comparing the options | Concern | Read `Current` inside | Pass as a parameter | |---|---|---| | Visibility of the dependency | hidden | in the signature | | Works in console, jobs, rake | only if someone set `Current` | always | | Test setup | set globals per test | pass an argument | | Boilerplate | low | higher in deep call chains | | Good fit | audit defaults, request ids | decisions, scoping, permissions | ## Migrating away from hidden reads When a codebase already reads `Current` deep in its models, the refactor can be gradual: 1. Add an explicit parameter with a default, `def editable_by?(user = Current.user)`, so existing callers keep working. 2. Update callers one by one to pass the value. 3. Remove the default once no caller relies on it, which turns the hidden dependency into a visible one. ## When to accept the trade-off Current is not wrong; it is a sharp tool. Request ids for log correlation, the acting user for audit trails and the account for association defaults are exactly the cross-cutting values it was designed for, and threading them through every method would add noise without making anything safer. The judgement an interviewer looks for is the boundary: implicit context for bookkeeping, explicit arguments for behaviour. A practical review question is: "Would this method still be correct if called from the console with `Current` empty?" If not, it should take the value as an argument.
- What goes wrong with `default_scope { where(account: Current.account) }` in a rake task?Nothing sets `Current.account` in a rake task, so the scope becomes `WHERE account_id IS NULL` and every query returns no tenant rows, or, if someone adds `unscoped` to make it work, all tenants' rows. Scope explicitly instead, through `account.contacts`, and pass the account to the task.
- How would you make the console safe for support staff when models read `Current.user` for audit fields?Keep the audit defaults optional, so `creator` can also be assigned explicitly, and wrap console sessions or one-off scripts in `Current.set(user: support_user) { ... }`. That way records created by hand still carry an author, and nothing that makes decisions depends on `Current` being set.
Current is like the name badge a visitor wears in an office building: handy for the reception log and the coffee machine, but a door that grants access based on whoever's badge happens to be nearest, rather than the person in front of it, will one day open for the wrong person.
- Current is safe for any data because it resets after each request.
- Reading Current inside model methods is fine since every caller is a controller.
- A default_scope on Current.account is a safe way to enforce tenancy everywhere.
- Passing user and account as arguments is always better, so Current should never be used.
- Controller-specific values belong in Current so views and helpers can reach them.