skip to content

Active Support

Active Support is the library under every Rails framework: core class extensions, ActiveSupport::Concern, CurrentAttributes, zone-aware time and Notifications. Interviewers probe its magic.

part ofRuby on Railsread it →
on this pageshow

explore

questions

28

In a Rails app, what is a model concern, where does it live, and how would you share soft-delete behaviour across several models with one?

level: juniorimportance: must knowfreq 62%

answer

  1. a module that extends ActiveSupport::Concern
  2. app/models/concerns is generated
  3. included do for scopes and callbacks
  4. class_methods do for class-level methods
  5. include SoftDeletable in each model

basics

~20 s

A concern is a module that extends ActiveSupport::Concern, kept in app/models/concerns (or app/controllers/concerns). Its included block declares scopes and callbacks on the host, class_methods adds class methods, and plain defs become instance methods; each model then writes include SoftDeletable.

solid answer

~40 s

A concern is an ordinary Ruby module that calls `extend ActiveSupport::Concern`, which gives it two hooks. Code in `included do ... end` runs inside the including class, so it can declare `scope :kept`, validations, callbacks or associations exactly as the model body would. Methods inside `class_methods do ... end` become class methods, and plain `def`s in the module become instance methods. `rails new` creates `app/models/concerns` and `app/controllers/concerns`, and each is its own autoload root, so `app/models/concerns/soft_deletable.rb` defines `SoftDeletable`, not `Concerns::SoftDeletable`. In a document-archive app, `Document`, `Folder` and `Note` each write `include SoftDeletable` and gain `kept` and `trashed` scopes, `soft_delete` and `restore`, as long as each table has a `deleted_at` column.

code

ruby · 10 lines
ruby
class Folder < ApplicationRecord
  include SoftDeletable
  has_many :documents
end

Folder.kept.count                          # WHERE deleted_at IS NULL
folder = Folder.first
folder.soft_delete                         # sets deleted_at
folder.trashed?                            # => true
Folder.purge_trashed_before(30.days.ago)   # class method from class_methods

go deeper

for a junior

Recall the shape: extend ActiveSupport::Concern, an included block for scopes and callbacks, class_methods for class methods, defs for instance methods, and the generated concerns folders.

for a middle

Explain why scope must sit in the included block, how class_methods becomes the class's methods, and what the concern assumes about the host's columns.

for a senior

Show you would document and test a concern's contract with its hosts, and keep it to the host's public API.

for a principal

Decide which shared behaviours deserve a concern at all, and how a team names and reviews them so concerns stay roles rather than a place to move code.

## The problem a concern solves A document-archive app lets users trash documents, folders and notes and restore them for thirty days. Each of those models needs the same pieces: a `deleted_at` column, scopes that hide or show trashed rows, methods to trash and restore a record, and a class-level purge for old trash. Copying that code into three models invites drift. A **concern** is the Rails way to write it once and mix it into each model. ## What a concern is A concern is a plain Ruby module that calls **`extend ActiveSupport::Concern`**. That one line adds three things a bare module lacks: - an **`included do ... end`** block, whose body runs in the context of the class that includes the module; - a **`class_methods do ... end`** block, whose methods become class methods of that class; - automatic handling of concerns that depend on other concerns. Everything else is ordinary module code: a `def` in the module body becomes an instance method of every including class. ```ruby # app/models/concerns/soft_deletable.rb module SoftDeletable extend ActiveSupport::Concern included do scope :kept, -> { where(deleted_at: nil) } scope :trashed, -> { where.not(deleted_at: nil) } end class_methods do def purge_trashed_before(time) trashed.where(deleted_at: ...time).destroy_all end end def soft_delete = update(deleted_at: Time.current) def restore = update(deleted_at: nil) def trashed? = deleted_at.present? end ``` ## Using it in a model ```ruby class Document < ApplicationRecord include SoftDeletable belongs_to :folder end ``` After `include SoftDeletable`, `Document.kept`, `Document.purge_trashed_before(30.days.ago)` and `document.soft_delete` all work, and so do the same calls on `Folder` and `Note` once they include it. Why the blocks matter: 1. `scope` is a class method of Active Record models. Written directly in the module body it would run on the module, which has no `scope` method; inside `included do` it runs on `Document`. 2. `purge_trashed_before` must be callable on the class, so it goes in `class_methods`. 3. `soft_delete`, `restore` and `trashed?` work on one record, so they are plain instance methods. ## Where concerns live `rails new` creates two folders with a `.keep` file each: | Folder | Typical contents | |---|---| | `app/models/concerns` | shared model roles: `SoftDeletable`, `Searchable`, `Taggable` | | `app/controllers/concerns` | shared controller behaviour, such as before_actions or `rescue_from` handlers | Each `concerns` folder is configured as its own root, so the file name maps to a top-level constant: `soft_deletable.rb` defines `SoftDeletable`. A concern used by only one model can also live in a folder named after it, for example `app/models/document/versioning.rb` defining `Document::Versioning`. ## Controller concerns work the same way The same module shape serves controllers. A concern in `app/controllers/concerns` can declare `before_action :set_folder` inside `included do`, add a `rescue_from` handler, or expose a helper with `helper_method`, and every controller that includes it gains them. The archive app might share a `FolderScoped` concern between `DocumentsController` and `NotesController`, so both load the current folder the same way. As with models, the `included` block runs with `self` set to the controller class, which is why those class-level macros work there. ## The contract a concern assumes A concern silently relies on its host. `SoftDeletable` assumes a `deleted_at` datetime column, so each including model needs a migration that adds it, ideally with an index if `kept` is used on large tables. Good concerns state that contract in a comment at the top, and keep to the host's public API (columns and public methods) rather than reaching into another concern's private helpers. ## Common mistakes - Forgetting `extend ActiveSupport::Concern`, after which `included do` raises `ArgumentError`, because Ruby's own `Module#included` hook expects the including class as an argument. - Writing `scope :kept, ...` at the top level of the module instead of inside `included do`. - Putting a class-level method in the module body and wondering why `Document.purge_trashed_before` is undefined. - Including the concern in a model whose table lacks `deleted_at`, which fails only when a scope or method first touches the column.

  • Where would you put the `deleted_at` column, and how do you make sure every including model has it?
    Each model's table needs its own migration, such as `add_column :folders, :deleted_at, :datetime` plus an index if `kept` filters large tables. The concern cannot create columns. Document the requirement at the top of the concern, and cover it with a test that runs against every including model so a missing column fails in CI rather than in production.
  • What goes wrong if `scope :kept` is written directly in the module body instead of inside `included do`?
    The module body runs once, when the file loads, with `self` being the module itself. `SoftDeletable` has no `scope` method, so loading the file raises `NoMethodError`. Inside `included do`, the same line runs with `self` set to `Document`, `Folder` or `Note`, which do have `scope`.

  • A concern is a Rails class you inherit from, like ApplicationRecord.
  • Scopes can be declared at the top level of a concern module.
  • app/models/concerns/soft_deletable.rb must define Concerns::SoftDeletable.
  • Including a concern adds the deleted_at column to the model's table.
  • Plain defs in a concern become class methods of the including model.
open as a page

In Rails, how do Active Support's blank?, present? and presence differ from Ruby's nil? and empty?, and what does each return?

level: juniorimportance: must knowfreq 72%

basics

~20 s

blank? is true for nil, false, whitespace-only strings and empty collections; present? is its negation; presence returns the receiver when present and nil otherwise. Ruby's nil? only matches nil, and empty? does not exist on nil.

open as a page

In Rails, why should application code call Time.current and Date.current rather than Time.now and Date.today?

level: juniorimportance: must knowfreq 72%

basics

~20 s

Time.now and Date.today use the server process's zone (ENV['TZ']); Time.current and Date.current use Time.zone, the app's configured or per-request zone. Mixing them shifts wall-clock times by the offset and, near midnight, gives a different date.

open as a page

In a Rails model, what does delegate :status, to: :rsvp, prefix: true, allow_nil: true generate, and what changes without allow_nil?

level: middleimportance: must knowfreq 52%

basics

~10 s

It defines rsvp_status, which calls rsvp.status and returns nil when rsvp is nil. Without allow_nil: a nil rsvp raises ActiveSupport::DelegationError, a NoMethodError subclass naming the method and the nil target.

open as a page

In Rails 8.1, when exactly are Current attributes reset, and what do the before_reset and resets hooks on a CurrentAttributes class run?

level: middleimportance: must knowfreq 42%

basics

~20 s

The Rails executor wraps each request and job; when it completes, CurrentAttributes.clear_all runs every instance's reset callbacks and discards the instances, so the next execution builds fresh ones from the defaults. before_reset runs before the values are cleared, resets after.

open as a page

In a Rails app, what do the sql.active_record and process_action.action_controller events carry, and how would you use them to catch slow queries and actions?

level: middleimportance: must knowfreq 40%

basics

~20 s

sql.active_record fires per query with the SQL, its name ("Order Load"), binds, row_count and a cached flag; process_action.action_controller fires per action with controller, action, filtered params, status, view_runtime and db_runtime. Subscribe and compare event.duration with a threshold.

open as a page

In a Rails app, how do config.time_zone and config.active_record.default_timezone split the work of storing and showing timestamps?

level: middleimportance: must knowfreq 58%

basics

~10 s

config.active_record.default_timezone (:utc by default) sets the zone Active Record writes to and reads from datetime columns; config.time_zone sets Time.zone, into which datetime attributes are converted on read and in which assigned strings are parsed.

open as a page

In Rails, how do Array#to_sentence and String inflections such as pluralize, tableize and parameterize turn guest data into readable text?

level: juniorimportance: should knowfreq 38%

basics

~10 s

to_sentence joins an array as "Ana, Ben, and Cy" with configurable, I18n-aware connectors. String inflections rewrite words: pluralize(count), singularize, camelize, underscore, tableize, classify, humanize, titleize and parameterize for slugs.

open as a page

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%

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.

open as a page

In Rails, how do ActiveSupport::Notifications.instrument and ActiveSupport::Notifications.subscribe work together, and what does a subscriber receive?

level: juniorimportance: should knowfreq 32%

basics

~20 s

ActiveSupport::Notifications.instrument(name, payload) { ... } runs and times a block, then calls every subscriber whose pattern matches the name. A one-argument subscriber block gets an Event (name, payload, duration in ms); a five-argument block gets name, start, finish, id and payload.

open as a page

In ActiveSupport::Concern, what do the included and class_methods blocks actually do, and how does Concern resolve one concern depending on another?

level: middleimportance: should knowfreq 40%

basics

~20 s

included stores a block that Concern class_evals in the host; class_methods defines a ClassMethods module that the host extends. When a concern includes another concern, inclusion is deferred until a real class includes the outer one, so every block runs on that class.

open as a page

How do you test a Rails model concern such as SoftDeletable once, and still prove every model that includes it actually works?

level: middleimportance: should knowfreq 30%

basics

~20 s

Write the concern's tests once as a shared set, a test module included into each model's test or RSpec shared_examples, and run it against every including model, so each host's table, columns and callbacks are exercised.

open as a page

In a Rails app, what does 2.weeks.ago return, and why can 1.day.from_now differ from 24.hours.from_now?

level: middleimportance: should knowfreq 50%

basics

~20 s

2.weeks is an ActiveSupport::Duration and .ago subtracts it from Time.current, giving a time two weeks back. Days, weeks, months and years move the calendar and keep the wall-clock time; hours move by exact seconds, so they diverge across DST.

open as a page

In Rails, how do Active Support's try and try! differ, and when is Ruby's safe navigation operator &. the better choice?

level: middleimportance: should knowfreq 45%

basics

~20 s

Both return nil when the receiver is nil. try also returns nil when a non-nil receiver lacks the public method; try! raises NoMethodError then. Ruby's &. behaves like try!, so prefer &. and keep try for duck-typed receivers.

open as a page

In Rails 8.1 tests, how are Current attributes kept from leaking between tests, and how do you set Current.account for one test?

level: middleimportance: should knowfreq 25%

basics

~20 s

Rails clears Current around every test: a new app runs each test inside the executor, and older configurations clear it in setup and teardown. Assign Current.account in setup or wrap code in Current.set; requests and performed jobs start their own empty Current.

open as a page

In Rails, how do ActiveSupport::Subscriber and ActiveSupport::LogSubscriber turn events into method calls, and when would you write one instead of a subscribe block?

level: middleimportance: should knowfreq 22%

basics

~10 s

A class inheriting ActiveSupport::Subscriber calls attach_to :ticketing, and each public method becomes a subscription: checkout(event) receives checkout.ticketing as an Event. LogSubscriber adds a logger, level helpers and error rescue; detach_from removes a class's subscriptions.

open as a page

In Rails, what is ActiveSupport::TimeWithZone, and how do Time.zone.parse and in_time_zone produce one from strings and stored times?

level: middleimportance: should knowfreq 42%

basics

~20 s

ActiveSupport::TimeWithZone pairs a UTC instant with an ActiveSupport::TimeZone and shows it as that zone's local time. Time.zone.parse reads a string as wall-clock time in Time.zone; in_time_zone re-presents an existing time, date or string in a given zone.

open as a page

In a Rails controller, why apply a user's time zone with Time.use_zone in an around_action instead of assigning Time.zone in a before_action?

level: middleimportance: should knowfreq 48%

basics

~20 s

Time.zone= writes thread- or fiber-local state that Rails does not reset after a request, so a reused Puma thread hands it to the next request. Time.use_zone sets the zone only for its block and restores the previous one in an ensure.

open as a page

In a Rails codebase, when is a model concern a genuine role, when is it a junk drawer, and when should the code become a service object instead?

level: seniorimportance: should knowfreq 45%

basics

~20 s

A concern is a role when it names one cohesive trait several models share, like SoftDeletable. It is a junk drawer when it only moves unrelated methods out of a fat model. A multi-step process touching several models belongs in a plain object.

open as a page

In a plain Ruby gem that requires only active_support, why does 3.days raise NoMethodError, and how should the gem load just the extensions it uses?

level: seniorimportance: should knowfreq 28%

basics

~20 s

require "active_support" loads only what the framework itself needs, not most core extensions; a Rails app gets them because boot requires active_support/all. A gem should require "active_support" and then each file it uses, such as active_support/core_ext/integer/time.

open as a page

When does CurrentAttributes turn into hidden global state in a Rails codebase, and which values should you pass as explicit parameters instead?

level: seniorimportance: should knowfreq 38%

basics

~20 s

Current 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.

open as a page

In a multi-tenant Rails CRM, why is Current.account nil inside a job enqueued during the request, and how should the job get the account?

level: seniorimportance: should knowfreq 40%

basics

~20 s

Enqueuing serializes only the job's arguments; Current lives in the request's thread and is cleared when the request ends. The worker runs the job in a fresh execution with an empty Current, so pass account and user explicitly and set Current inside perform if needed.

open as a page

In a Rails app, why can one ActiveSupport::Notifications subscriber on sql.active_record slow down or break every request, and how do you keep it safe?

level: seniorimportance: should knowfreq 28%

basics

~20 s

Notifications subscribers run synchronously on the thread that fired the event, so their cost is paid on every query, and an exception they raise propagates into the query that fired it. Keep them filtered, cheap, I/O-free and rescued.

open as a page

A Rails freight-logistics app counts each depot's bookings before its 17:00 local cut-off; how do you build those daily windows so non-UTC depots and DST days stay correct?

level: seniorimportance: should knowfreq 34%

basics

~20 s

Build each window's bounds as wall-clock times in the depot's own ActiveSupport::TimeZone (previous day 17:00 to today 17:00) and query with those TimeWithZone values; Active Record sends them as UTC, and DST days come out 23 or 25 hours long.

open as a page

With ActiveSupport::Concern, what changes when a Rails model writes prepend Archivable instead of include Archivable, and what does the prepended block do?

level: middleimportance: nice to knowfreq 18%

basics

~20 s

prepend puts the concern in front of the model in method lookup, runs its prepended block (not its included block) on the model, and prepends ClassMethods to the model's singleton class, so the concern can wrap methods the model itself defines and call super.

open as a page

With ActiveSupport::Notifications, how does monotonic_subscribe differ from subscribe, and which clock does a one-argument Event subscriber use?

level: middleimportance: nice to knowfreq 14%

basics

~20 s

For five-argument subscribers, subscribe passes start and finish as wall-clock Time objects, while monotonic_subscribe passes Floats from Process::CLOCK_MONOTONIC, which never jump. A one-argument subscriber gets an Event timed on the monotonic clock either way; event.duration is milliseconds.

open as a page

In Rails 8.1, what does Rails.event add over ActiveSupport::Notifications, and how do notify, tagged and set_context shape a signup event?

level: middleimportance: nice to knowfreq 18%

basics

~10 s

Rails.event, new in Rails 8.1, reports structured, untimed events: notify("user.signed_up", user_id: 42) builds a hash with name, payload, tags, context, a nanosecond timestamp and source location, and passes it to every subscriber's emit method.

open as a page

In Rails 8.1, what does to_time return for a TimeWithZone, a DateTime and a Date, and what became of to_time_preserves_timezone?

level: seniorimportance: nice to knowfreq 14%

basics

~20 s

In Rails 8.1, TimeWithZone#to_time returns a Ruby Time that keeps the receiver's zone and DateTime#to_time keeps its offset; the system-local option is gone and to_time_preserves_timezone is deprecated. Date#to_time and String#to_time still use the process zone.

open as a page