With ActiveSupport::Concern, what changes when a Rails model writes prepend Archivable instead of include Archivable, and what does the prepended block do?
answer
- prepend_features instead of append_features
- prepended do runs, included do does not
- ClassMethods prepended to the singleton class
- dependencies are prepended too
- wrap a method the model defines itself
basics
~20 sprepend 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.
solid answer
~50 sConcern supports `prepend` as well as `include`. `prepend Archivable` goes through Concern's `prepend_features`: dependencies are prepended first, the module is placed before the model in the ancestor chain, `ClassMethods` is prepended to the model's singleton class rather than extended, and the `prepended do ... end` block is `class_eval`ed on the model. The `included` block does **not** run in that path, so a concern written only with `included do` loses its scopes and callbacks when someone prepends it. You prepend when the concern must wrap a method the model defines in its own body, such as `Document#archive!`: an included module sits behind the class and its version would never be reached. Methods inherited from Active Record, like `destroy`, can be wrapped from an included concern because the module still sits in front of them. A second `prepended` block raises `MultiplePrependBlocks`.
code
ruby · 12 linesmodule Archivable
extend ActiveSupport::Concern
included do
scope :archived, -> { where.not(archived_at: nil) }
end
end
class Folder < ApplicationRecord
prepend Archivable
end
Folder.archived # NoMethodError: the included block never rango deeper
Recall that concerns can be prepended as well as included, and that prepended do is the block that runs then.
Explain what Concern's prepend path does to the module, ClassMethods and dependencies, and why the included block is skipped.
Know when prepend is actually required, a method defined in the model body, and avoid it otherwise because it hides control flow.
Weigh method-wrapping concerns against callbacks or explicit service code when several teams' concerns wrap the same model methods.
## Why a concern would be prepended In the document-archive app, `Document` defines its own `archive!` method in the class body. An auditing requirement arrives: every archive must be logged with the user and time, for documents and for folders. A concern looks like the right home, but there is a lookup problem. An **included** module sits *behind* the class in the ancestor chain, so `Document#archive!` is found first and the concern's version never runs. A **prepended** module sits *in front of* the class, so its `archive!` runs first and can call `super` to reach the model's own method. ## How Concern handles `prepend` `ActiveSupport::Concern` overrides `prepend_features` as well as `append_features`. When a class writes `prepend AuditedArchive`: 1. If the class already has the module among its ancestors, nothing happens. 2. The concern's dependencies are **prepended** to the class first. 3. The module itself is prepended. 4. If the concern defines `ClassMethods`, that module is **prepended to the class's singleton class**, so it can also wrap class methods the model defines with `def self.`. 5. The **`prepended do ... end`** block is `class_eval`ed on the class. The parallel with `include` is close, with one sharp difference: the `included` block is never run on the prepend path, and the `prepended` block is never run on the include path. | | `include Concern` | `prepend Concern` | |---|---|---| | Position in lookup | after the class | before the class | | Block that runs | `included do` | `prepended do` | | `ClassMethods` | `extend`ed onto the class | prepended to the singleton class | | Dependencies | included | prepended | | Second block of the same kind | `MultipleIncludedBlocks` | `MultiplePrependBlocks` | ## A worked example ```ruby module AuditedArchive extend ActiveSupport::Concern prepended do has_many :archive_events, as: :subject end def archive!(by:) super.tap { archive_events.create!(user: by) } end end class Document < ApplicationRecord prepend AuditedArchive def archive!(by:) update!(archived_at: Time.current) end end ``` `document.archive!(by: user)` now enters `AuditedArchive#archive!`, which calls `super` into `Document#archive!` and then records the event. With `include` instead, `Document#archive!` would win and no event would be written, without any error. ## When you do not need `prepend` Most Active Record methods a concern wants to wrap are not defined in the model class but in modules that `ActiveRecord::Base` pulls in. An included concern sits in front of those modules and behind the model: - wrapping `destroy` to soft-delete instead works from an `include`d concern, as long as the model itself does not define `destroy`; - callbacks such as `before_destroy` usually beat overriding anyway, because they compose with other concerns. So the honest rule is narrow: prepend when the method you wrap is defined in the class body (or as a `def self.` class method there), or when the concern must win over methods included later. ## Checking which version runs Ruby's introspection confirms the order after a prepend: - `Document.ancestors.first(2)` returns `[AuditedArchive, Document]`; - `document.method(:archive!).owner` is `AuditedArchive`; - `document.method(:archive!).super_method.owner` is `Document`. With `include`, the first owner would be `Document` and the concern's method would only be reachable through `super` from the model, which the model never calls. ## Traps 1. **A concern written for `include` and then prepended.** If it declares its scopes inside `included do`, `prepend` skips that block and the scopes silently never exist. A concern meant to support both must use both blocks. 2. **Prepending for no reason.** A prepended module intercepts every call to the methods it defines, which surprises readers of the model, who see `def archive!` and expect it to be the first code to run. 3. **Order between several prepended concerns.** The last one prepended runs first; listing them in a different order changes which wrapper sees the call first. `Module#concerning` supports the same choice inline: `concerning :Auditing, prepend: true do ... end` defines a `Document::Auditing` concern inside the class and prepends it.
- How would you write a concern that works whether a model includes or prepends it?Put the shared declarations in a private class method or a lambda and call it from both `included do` and `prepended do`, since each path runs only its own block. Keep the instance methods free of assumptions about their position, and test both forms if both are supported.
- Why can an included concern override `destroy` on an Active Record model without `prepend`?`destroy` is defined in modules mixed into `ActiveRecord::Base`, not in the model class. An included concern sits between the model and `ActiveRecord::Base`, so method lookup reaches the concern's `destroy` first and `super` continues to Active Record's. Prepend is needed only when the model class defines the method itself.
- Prepending a concern also runs its included block.
- prepend and include give a concern the same position in method lookup.
- ClassMethods is extended the same way whether the concern is included or prepended.
- An included concern can never override an Active Record method like destroy.
- A concern can declare as many prepended blocks as it likes.