skip to content

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%

answer

  1. included block is class_eval'd in the host
  2. class_methods builds a ClassMethods module
  3. base.extend ClassMethods on include
  4. nested concerns are deferred to the host
  5. MultipleIncludedBlocks on a second block

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.

solid answer

~40 s

`included do` does not run anything when the concern is defined; it stores the block. When a class includes the concern, Concern's `append_features` includes the concern's own dependencies first, then the module, then extends the host with `ClassMethods` and `class_eval`s the stored block, so `self` inside it is the host class. `class_methods do` creates (or reopens) a `ClassMethods` constant inside the concern. The dependency rule is the part plain modules lack: if `Purgeable` includes `SoftDeletable` and both are concerns, `SoftDeletable` is not applied to `Purgeable`; it is recorded and applied to whatever class later includes `Purgeable`, before `Purgeable` itself. Without it, `SoftDeletable`'s block would run on a module that has no `scope`. Including a concern twice is a no-op, and a second `included` block from another location raises `MultipleIncludedBlocks`.

code

ruby · 16 lines
ruby
module Purgeable
  extend ActiveSupport::Concern
  include SoftDeletable # recorded as a dependency, not applied here

  class_methods do
    def purge_window = 30.days
  end
end

class Note < ApplicationRecord
  include Purgeable
end

Note.kept          # scope from SoftDeletable's included block, run on Note
Note.purge_window  # => 30 days
Note.ancestors.take(3) # => [Note, Purgeable, SoftDeletable]

go deeper

for a junior

Recall that the included block runs inside the including class and that class_methods gives that class its class methods.

for a middle

Walk through append_features: dependencies, the module, ClassMethods, then the block, and explain how a nested concern is deferred to the host.

for a senior

Use the dependency rule to compose concerns safely, and know the MultipleIncludedBlocks and double-include behaviours when debugging a concern stack.

for a principal

Judge how deep concern-on-concern stacks should go before the implicit ordering becomes harder to reason about than an explicit object.

## What `extend ActiveSupport::Concern` changes Ruby already gives modules an `included(base)` hook and lets you `base.extend(ClassMethods)` by hand. **`ActiveSupport::Concern`** wraps that pattern and changes when and where code runs. Extending a module with it does three things: it starts an empty list of dependencies, it replaces `included` with a version that *stores* a block, and it overrides `append_features`, the method Ruby calls during `include`. ## Step by step: what `include SoftDeletable` does When `Document` writes `include SoftDeletable`, Concern's `append_features(Document)` runs: 1. **Already included?** If `Document` already has `SoftDeletable` among its ancestors, it returns at once, so including a concern twice does nothing. 2. **Dependencies first.** Every concern that `SoftDeletable` itself included is now included into `Document`. 3. **The module itself.** Ruby's normal inclusion puts `SoftDeletable`'s instance methods into `Document`'s ancestor chain. 4. **Class methods.** If the concern has a `ClassMethods` constant, `Document.extend(SoftDeletable::ClassMethods)` runs. 5. **The stored block.** The `included` block is `class_eval`ed on `Document`, so `scope`, `has_many`, `validates` and `before_destroy` inside it run as if written in the model. `class_methods do ... end` is a shortcut for `module ClassMethods ... end`: it creates the constant, or reopens it if the concern already defines one, so the two styles can even be mixed. ## The dependency problem Suppose the archive app adds a second concern that builds on the first: ```ruby module Purgeable extend ActiveSupport::Concern include SoftDeletable included do after_commit :schedule_purge, if: :trashed? end end class Note < ApplicationRecord include Purgeable # SoftDeletable comes along end ``` With plain Ruby modules and hand-written hooks, `include SoftDeletable` inside `Purgeable` would fire `SoftDeletable`'s hook with `Purgeable` (a module) as the base, and `scope :kept` would fail because a module has no `scope`. The usual workaround was to make every model include the inner module first, by hand, in the right order. Concern detects that the including side is itself a concern. Instead of applying `SoftDeletable` to `Purgeable`, it **records it as a dependency**. Later, when `Note` includes `Purgeable`, step 2 above includes `SoftDeletable` into `Note` first, so its block runs on `Note`, and only then is `Purgeable` applied. The model writes one line and the order is handled for it. ## Rules and errors worth knowing | Situation | What happens | |---|---| | Two `included` blocks in one concern, from different places | raises `ActiveSupport::Concern::MultipleIncludedBlocks` | | The same file reloaded in development | allowed: the check compares the block's source location | | A concern included twice into one class | second include is ignored | | `included do` in a module without `extend ActiveSupport::Concern` | `ArgumentError`: Ruby's `included` expects the base class | | Both `module ClassMethods` and `class_methods do` | merged into one module | ## Inspecting the result Because everything ends up on the host, the console shows what a concern stack did: - `Note.ancestors` lists `Purgeable` and `SoftDeletable` in the order they were applied; - `Note.singleton_class.include?(SoftDeletable::ClassMethods)` confirms the class methods were extended; - `Note.instance_method(:soft_delete).owner` names the module that defined an instance method. This is the quickest way to answer "where does this method come from" in a model that includes several concerns. ## Why this matters in an interview The question separates people who have used concerns from people who know what they do. The points to make: - the `included` block is deferred code run with the host as `self`, not code run when the module loads; - `class_methods` is just a `ClassMethods` module that Concern extends for you; - dependency resolution is the feature with no one-line plain-Ruby equivalent, and it is what lets concerns build on each other; - the order is deterministic: dependencies, then the module, then class methods, then the block. It also explains a debugging habit: when a scope or callback from a concern behaves oddly, look for where the `included` block ran, which is always the final host class.

  • Why does Concern compare source locations before raising `MultipleIncludedBlocks`?
    In development, code reloading can evaluate the same concern file again, which calls `included` a second time with an equivalent block. Comparing source locations lets that pass, while a genuine second `included` block written elsewhere in the module still raises, because only one block is stored and the other would be silently lost.
  • If `Purgeable` includes `SoftDeletable`, is `SoftDeletable` in `Purgeable.ancestors`?
    No. When the including side is itself a concern, Concern's `append_features` only records the dependency and does not call Ruby's normal inclusion, so `Purgeable.ancestors` lacks `SoftDeletable`. It appears in the ancestors of the class that includes `Purgeable`, which is where its methods and block are applied.

A concern's included block is like assembly instructions packed in a flat-pack box: nothing is built when the box is packed. If one box contains another kit, the instructions for the inner kit are not followed inside the box; both sets are followed in the room where the furniture finally goes, inner kit first.

  • The included block runs once, when the concern file is loaded.
  • Inside the included block, self is the concern module.
  • When one concern includes another, the inner one's included block runs on the outer module.
  • class_methods copies its methods into every instance of the host.
  • Including the same concern twice runs its included block twice.