skip to content

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%

answer

  1. attach_to :namespace
  2. method name is the event prefix
  3. sql(event) handles sql.active_record
  4. detach_from removes a class
  5. LogSubscriber adds logger and rescue

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.

solid answer

~50 s

`ActiveSupport::Subscriber` maps a namespace to methods. `attach_to :ticketing` instantiates the class and subscribes each public method to `"<method>.ticketing"`, so `def checkout(event)` handles `checkout.ticketing`; methods defined later are subscribed too, and `start` and `finish` are never treated as events. Each handler receives an `ActiveSupport::Notifications::Event`. `detach_from :ticketing` removes every subscription of that class, which is how you switch off a framework subscriber such as `ActiveRecord::LogSubscriber.detach_from(:active_record)` without touching anyone else's. `ActiveSupport::LogSubscriber` builds on it for logging: a `logger` (Rails.logger), `info`/`debug`/`error` helpers, `color`, `subscribe_log_level` so events are skipped when the log level would discard them, and a `call` that rescues handler errors and reports them instead of failing the request. Write a class when you handle a family of events, want it testable and detachable, or are building a log or metrics integration; use a block for one event.

code

ruby · 17 lines
ruby
# app/subscribers/ticketing_metrics.rb
class TicketingMetrics < ActiveSupport::Subscriber
  attach_to :ticketing

  def checkout(event)            # checkout.ticketing
    record("checkout", event.duration)
  end

  def refund(event)              # refund.ticketing
    record("refund", event.duration)
  end

  private
    def record(kind, ms)        # private: not an event handler
      MetricsBuffer.push(kind, ms)   # your own in-memory buffer
    end
end

go deeper

for a junior

Recall that a subscriber class uses attach_to :namespace and that each public method name is the first part of the event name it handles.

for a middle

Explain the method-to-event mapping, method_added, detach_from, and what LogSubscriber adds: logger, level helpers, silencing and rescue.

for a senior

Choose between blocks and classes for an integration, keep helpers private, isolate handler errors, and use detach_from to replace a framework subscriber safely.

for a principal

Make subscriber classes the house pattern for integrations so each is reviewable, testable and switchable per environment.

## Subscriber: a namespace as a class `ActiveSupport::Subscriber` turns a set of events into **one object with one method per event**: 1. `attach_to :ticketing` creates an instance (or takes one you pass) and records the namespace. 2. Every **public instance method** defined on the class becomes a subscription to `"<method_name>.ticketing"`. With `inherit_all: true`, public methods inherited from a parent subscriber class are included too. 3. A `method_added` hook subscribes methods defined **after** `attach_to`, so the call can sit at the top or the bottom of the class. 4. `start` and `finish` are excluded, because those names mean something else to the fanout. 5. When an event arrives, `call(event)` takes the part of the name before the first dot and `send`s it, passing an `ActiveSupport::Notifications::Event`. `detach_from :ticketing` finds the attached instance of **that exact class** and unsubscribes every pattern it registered. ## How Rails itself uses it Every framework ships subscriber classes attached at load time, for example: - `ActiveRecord::LogSubscriber.attach_to :active_record` — writes the SQL lines in the development log from `sql(event)`. - `ActionController::LogSubscriber.attach_to :action_controller` — writes the "Processing by…" and "Completed 200 OK…" lines. - In Rails 8.1, `ActiveSupport::StructuredEventSubscriber` subclasses such as `ActionController::StructuredEventSubscriber` re-emit the same events through `Rails.event`. Because they are classes, you can turn one off precisely with `detach_from`, which leaves other subscribers to the same events untouched. ## LogSubscriber: Subscriber plus logging plumbing | Feature | Subscriber | LogSubscriber | |---|---|---| | Namespace mapping, `attach_to`, `detach_from` | yes | yes (inherited) | | `logger` | — | `Rails.logger` by default; frameworks override it | | Level helpers | — | `info`, `debug`, `warn`, `error`, `fatal`, `unknown` | | Colour | — | `color(text, color, mode)`, honouring `colorize_logging` | | Skipping work by level | — | `subscribe_log_level :sql, :debug` marks the event **silenced** when the logger is above that level | | Handler raises | error reaches the instrumented code | rescued, sent to `ActiveSupport.error_reporter`, and logged as "Could not log … event" | Silencing matters for performance: a silenced log subscriber does not count as listening, so an event with no other subscribers is not timed at all. ## When a class beats a block - **A family of events** — `checkout`, `refund` and `seat_hold` under `.ticketing` read better as three methods than as three blocks or one Regexp with a `case`. - **Testability** — call `subscriber.checkout(event)` with a hand-built `Event` in a unit test. - **Switching off** — `detach_from` removes exactly your subscriptions; `ActiveSupport::Notifications.unsubscribe("checkout.ticketing")` would remove everyone's subscriptions with that name. - **Logging integrations** — inherit `LogSubscriber` to get level-aware silencing and error isolation for free. A block stays the right tool for a single event in an initializer. ## Testing a subscriber class - Instantiate it without attaching and call a handler with an `Event` captured from a real instrumentation: wrap `ActiveSupport::Notifications.instrument("checkout.ticketing", order_id: 1) { }` in `ActiveSupport::Notifications.subscribed(->(event) { captured = event }, "checkout.ticketing")`. - Or attach it in the test's setup, instrument the event, assert on the side effect, and call `detach_from` in teardown so other tests are unaffected. - For a `LogSubscriber`, point `ActiveSupport::LogSubscriber.logger` at an in-memory logger with the `logger=` writer and assert on what it wrote. ## Pitfalls - Public helper methods become subscriptions too; keep helpers `private`. - `ActiveSupport::Subscriber` has no rescue; wrap risky handlers yourself or inherit `LogSubscriber`. - Calling `attach_to` twice creates a second instance and subscribes it as well, so each event is handled twice; only redefining a method on an already attached class is guarded against duplicates.

  • Why should helper methods in an ActiveSupport::Subscriber subclass be private?
    `attach_to` and the `method_added` hook subscribe every public instance method to `"<name>.<namespace>"`. A public `format_duration` helper in a class attached to `:ticketing` would be subscribed to `format_duration.ticketing`. It is harmless until someone publishes that name, but it is noise in the subscription list and a trap; private methods are skipped.
  • How does subscribe_log_level make a LogSubscriber cheaper in production?
    `subscribe_log_level :sql, :debug` registers a check that reports the event as silenced whenever the logger would discard debug messages. Silenced subscribers are skipped by the fanout and do not count for `listening?`, so with the production default log level of info, the SQL log subscriber neither formats lines nor, on its own, forces the event to be timed.

  • attach_to :ticketing subscribes the class to every ticketing event in one catch-all handler
  • Private methods in an ActiveSupport::Subscriber become event handlers too
  • ActiveSupport::Subscriber rescues handler errors just like LogSubscriber
  • unsubscribe("sql.active_record") removes only Active Record's log subscriber
  • A method named checkout handles ticketing.checkout events