module TestProf::Rails::LoggingHelpers

Add `with_logging` and `with_ar_logging helpers`

Attributes

logger[W]

Public Class Methods

all_loggables() click to toggle source

rubocop:disable Metrics/CyclomaticComplexity rubocop:disable Metrics/PerceivedComplexity

# File lib/test_prof/recipes/logging.rb, line 29
def all_loggables
  return @all_loggables if instance_variable_defined?(:@all_loggables)

  @all_loggables = [
    ::ActiveSupport::LogSubscriber,
    ::Rails,
    defined?(::ActiveRecord::Base) && ::ActiveRecord::Base,
    defined?(::ActiveJob::Base) && ::ActiveJob::Base,
    defined?(::ActionView::Base) && ::ActionView::Base,
    defined?(::ActionMailer::Base) && ::ActionMailer::Base,
    defined?(::ActionCable::Server::Base.config) && ::ActionCable::Server::Base.config,
    defined?(::ActiveStorage) && ::ActiveStorage
  ].compact
end
ar_loggables() click to toggle source
# File lib/test_prof/recipes/logging.rb, line 18
def ar_loggables
  return @ar_loggables if instance_variable_defined?(:@ar_loggables)

  @ar_loggables = [
    ::ActiveRecord::Base,
    ::ActiveSupport::LogSubscriber
  ]
end
logger() click to toggle source
# File lib/test_prof/recipes/logging.rb, line 12
def logger
  return @logger if instance_variable_defined?(:@logger)

  @logger = Logger.new($stdout)
end
restore_logger(was_loggers, loggables) click to toggle source
# File lib/test_prof/recipes/logging.rb, line 54
def restore_logger(was_loggers, loggables)
  loggables.each_with_index do |loggable, i|
    loggable.logger = was_loggers[i]
  end
end
swap_logger(loggables) click to toggle source

rubocop:enable Metrics/CyclomaticComplexity rubocop:enable Metrics/PerceivedComplexity

# File lib/test_prof/recipes/logging.rb, line 46
def swap_logger(loggables)
  loggables.map do |loggable|
    was_logger = loggable.logger
    loggable.logger = logger
    was_logger
  end
end

Public Instance Methods

with_ar_logging() { || ... } click to toggle source
# File lib/test_prof/recipes/logging.rb, line 69
def with_ar_logging
  *loggers = LoggingHelpers.swap_logger(LoggingHelpers.ar_loggables)
  yield
ensure
  LoggingHelpers.restore_logger(loggers, LoggingHelpers.ar_loggables)
end
with_logging() { || ... } click to toggle source

Enable verbose Rails logging within a block

# File lib/test_prof/recipes/logging.rb, line 62
def with_logging
  *loggers = LoggingHelpers.swap_logger(LoggingHelpers.all_loggables)
  yield
ensure
  LoggingHelpers.restore_logger(loggers, LoggingHelpers.all_loggables)
end