skip to content

In a Rails app, how do you declare and use a Current class built on ActiveSupport::CurrentAttributes to carry the acting user and account?

level: juniorimportance: should knowfreq 45%

answer

  1. class Current < ActiveSupport::CurrentAttributes
  2. attribute :account, :user
  3. default: takes a value or a lambda
  4. set in a before_action, read anywhere
  5. reset and set are reserved names

basics

~10 s

Subclass ActiveSupport::CurrentAttributes in app/models/current.rb, declare attribute :account, :user, assign them in a controller before_action, and read Current.account from models, mailers or views. Each request or job starts with fresh values.

solid answer

~40 s

Create `class Current < ActiveSupport::CurrentAttributes` (conventionally `app/models/current.rb`) and declare `attribute :account, :user`, optionally with `default:`, which takes a plain value (duplicated for each instance) or a lambda called whenever an instance is built. `attribute` defines readers and writers that work on the class, `Current.account = ...`, but store into a per-thread instance, so concurrent requests on different Puma threads never see each other's values. In a multi-tenant CRM, `ApplicationController` sets `Current.account` from the subdomain and `Current.user` from the signed-in user in a `before_action`; models then read them, for example `belongs_to :creator, class_name: "User", default: -> { Current.user }`. `Current.set(user: admin) { ... }` changes values for a block and restores them after. Names such as `set`, `reset` and `instance` are reserved and raise `ArgumentError`.

code

ruby · 13 lines
ruby
class Contact < ApplicationRecord
  belongs_to :account, default: -> { Current.account }
  belongs_to :creator, class_name: "User", default: -> { Current.user }
end

# inside a request where the before_action ran:
contact = Contact.create!(name: "Ada")
contact.account == Current.account # => true

Current.set(user: User.find_by!(email_address: "[email protected]")) do
  Contact.create!(name: "Imported")  # creator is the ops user
end
Current.user                         # back to the signed-in user

go deeper

for a junior

Recall the shape: subclass ActiveSupport::CurrentAttributes, declare attribute names, set them in a before_action, read Current.account anywhere in the request.

for a middle

Explain the per-thread instance behind the class accessors, how default: values and lambdas are applied, custom writers with super, and Current.set restoring values.

for a senior

Show restraint: keep Current to a few top-level values, and know which code paths, jobs, console, rake, never set it.

for a principal

Decide where ambient request context is acceptable in the architecture and where domain code must take explicit arguments instead.

## What `CurrentAttributes` is Some values are needed almost everywhere during one request: which **account** (tenant) the request belongs to, which **user** is acting, the request id for logs. Passing them as arguments through every controller, model and mailer is noisy. **`ActiveSupport::CurrentAttributes`** gives a class whose attributes behave like globals but are **isolated per thread** (or per fiber, if `config.active_support.isolation_level = :fiber`) and are discarded when the request or job finishes. ## Declaring the class ```ruby # app/models/current.rb class Current < ActiveSupport::CurrentAttributes attribute :account, :user attribute :request_id attribute :locale, default: -> { I18n.default_locale } def user=(user) super self.account ||= user&.account end end ``` What each line gives you: - **`attribute`** defines a reader and a writer for each name. They exist on the class (`Current.user`) and forward to a hidden instance, `Current.instance`, created lazily for the current thread. - **`default:`** sets the starting value. A lambda or proc is called each time an instance is created (and again on reset); any other value is copied with `dup`, so `default: []` gives each request its own array. - **Custom writers** can override the generated ones and call `super`, as `user=` does above to fill in the account. - Public **instance methods** you define, such as `def admin? = user&.admin?`, are also callable on the class: `Current.admin?`. ## Setting the values Values are usually assigned at the edge of the app, in a controller callback: ```ruby class ApplicationController < ActionController::Base before_action :set_current_account private def set_current_account Current.account = Account.find_by!(subdomain: request.subdomain) end end ``` Authentication code then sets `Current.user` for the signed-in user. Background jobs and scripts set values themselves, because nothing sets them automatically there. ## Reading the values Any code running in the same request can read them: | Where | Example | |---|---| | Model association default | `belongs_to :creator, class_name: "User", default: -> { Current.user }` | | Scoping a query | `Current.account.contacts.where(stage: "lead")` | | Audit callback | `before_create { self.request_id = Current.request_id }` | | View | `Current.user.name` in the layout | ## Temporarily changing values: `set` `Current.set(user: admin) { ... }` assigns the given attributes, runs the block and then restores the previous values, even if the block raises. It suits a console session, a job or an admin action that must act as another user for one operation. ## Where `Current` sits in one request The lifecycle of a CRM request, in order: 1. The executor starts a new execution for the request, so `Current` is empty apart from defaults. 2. `ApplicationController`'s callbacks assign `Current.account` and `Current.user`. 3. Controllers, models, mailers rendered inline and views read them. 4. When the response body is closed, the executor completes and the values are discarded. The next request on the same Puma thread repeats the cycle from step 1. ## Reserved names and other rules 1. **Reserved names.** `attribute` raises `ArgumentError` ("Restricted attribute names") for `set`, `reset`, `resets`, `instance`, `before_reset`, `after_reset`, `reset_all` and `clear_all`, because they would clash with the class's own API. 2. **One instance per class per thread.** `Current` and a second subclass such as `Current::Request` keep separate instances. 3. **`attributes`** returns a copy of the hash, so mutating it does not change `Current`. 4. **Nothing is persisted.** Values are gone when the request or job ends; the next one starts from the defaults. ## What to keep in it Rails' own documentation warns that a global like `Current` is easy to overdo: keep it to a few top-level values used by nearly every action, such as account, user and request details. Controller-specific data belongs in instance variables or method arguments.

  • Why can two requests on different Puma threads both write `Current.user` without clashing?
    The class-level accessors forward to `Current.instance`, which is stored per execution context: per thread by default, or per fiber when `config.active_support.isolation_level` is `:fiber`. Each thread therefore has its own instance and its own values, even though the code reads like a single global.
  • What is the difference between `default: []` and `default: -> { [] }` on a Current attribute?
    Both give each instance its own empty array. A non-proc default is copied with `dup` when an instance is built or reset, and a lambda is called at those moments. The lambda form matters when the value must be computed fresh, such as `-> { I18n.default_locale }`, or when `dup` would not give an independent copy.

  • Current is a plain class-level global, so threads share one set of values.
  • Current values are stored in the session and survive to the next request.
  • You can name a Current attribute reset as long as you never call reset.
  • Current.set changes the values permanently for the rest of the request.
  • A default: value is shared by every request as the same object.