Module: TestProf::Rails::LoggingHelpers

Defined in:
lib/test_prof/recipes/logging.rb

Overview

Add ‘with_logging` and `with_ar_logging helpers`

Class Attribute Summary collapse

Class Method Summary collapse

Instance Method Summary collapse

Class Attribute Details

.loggerObject



12
13
14
15
16
# File 'lib/test_prof/recipes/logging.rb', line 12

def logger
  return @logger if instance_variable_defined?(:@logger)

  @logger = Logger.new(STDOUT)
end

Class Method Details

.all_loggablesObject

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



29
30
31
32
33
34
35
36
37
38
39
40
41
42
# 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_loggablesObject



18
19
20
21
22
23
24
25
# 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

.restore_logger(was_loggers, loggables) ⇒ Object



54
55
56
57
58
# 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) ⇒ Object

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



46
47
48
49
50
51
52
# 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

Instance Method Details

#with_ar_loggingObject



69
70
71
72
73
74
# 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_loggingObject

Enable verbose Rails logging within a block



62
63
64
65
66
67
# 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