# What the change does
# Why this matters
Rails.console provides a hook that runs only when you start bin/rails console. That makes it a safe place to define interactive helpers that shouldn't be available in web or background job processes. Instead of repeating:
ActiveRecord::Base.logger.level = Logger::ERROR
you define helpers once and call them whenever you need quieter output.
# The implementation (high-level)
Create an initializer such as config/initializers/console_helpers.rb and register a block with Rails.application.console. Inside that block define three methods:
- disable_console_loggers!: store previous levels in an instance variable and set each logger's level to:error, returning a confirmation string.
Placing method definitions inside the console block defines them on Object in the interactive session (self in console is main, an Object), so they become available as plain helper methods in that console.
# Usage
After adding the initializer, start bin/rails console and run:
irb(main)> disable_console_loggers!
This toggles the logger verbosity in the live session without restarting.
# Alternative: silence a single block or query
If you only need to silence logging around a single query or section of code, use ActiveRecord::Base.logger.silence do... end. That affects only the enclosed code and doesn't require toggling global helper state.
# Practical notes and behavior
- The helper saves the previous logger levels so enabling restores the original settings rather than assuming a default.
- The implementation collects loggers with compact.uniq to avoid duplicates and to ignore absent loggers when ActiveRecord isn't loaded.
# When to use each approach
- Use disable_console_loggers! and enable_console_loggers! when you want a session-wide quieter console for copying results, experimenting, or reducing noise while working interactively.
- Use ActiveRecord::Base.logger.silence for tight, localized suppression around a specific query or block, preserving console output elsewhere.
# Quick checklist to add the helpers
- Create config/initializers/console_helpers.rb.
- Wrap method definitions in Rails.application.console do... end.
- Define console_loggers, disable_console_loggers!, and enable_console_loggers! as described.
- Restart the console to pick up the initializer and then call the helpers interactively.