Class: RuboCop::Cop::Legion::HelperMigration::LoggingGuard

Inherits:
Base
  • Object
show all
Defined in:
lib/rubocop/cop/legion/helper_migration/logging_guard.rb

Overview

Detects unnecessary guard checks around logging that are no longer needed. The ‘log` helper is always available in extensions via `Helpers::Lex`.

Catches two patterns:

  1. ‘respond_to?` checks for old logging methods or `log`

  2. ‘defined?(Legion::Logging)` guards

Examples:

# bad
log.warn(msg) if respond_to?(:log_warn, true)
log.info(msg) if respond_to?(:log)
Legion::Logging.info(msg) if defined?(Legion::Logging)

# good
log.warn(msg)
log.info(msg)

Constant Summary collapse

MSG_RESPOND_TO =
'`respond_to?(:%<method>s)` guard is unnecessary. ' \
'`log` is always available via `Helpers::Lex`.'
MSG_DEFINED =
'`defined?(Legion::Logging)` guard is unnecessary. ' \
'`Legion::Logging` is always loaded in the framework.'
OLD_METHODS =
%i[log log_info log_warn log_error log_debug log_fatal].to_set.freeze
RESTRICT_ON_SEND =
%i[respond_to?].freeze

Instance Method Summary collapse

Instance Method Details

#old_logging_respond_to?(node) ⇒ Object

respond_to?(:log_warn) or respond_to?(:log_warn, true)



36
37
38
# File 'lib/rubocop/cop/legion/helper_migration/logging_guard.rb', line 36

def_node_matcher :old_logging_respond_to?, <<~PATTERN
  (send nil? :respond_to? (sym $_) ...)
PATTERN

#on_defined?(node) ⇒ Boolean

defined? is a keyword, not a send — handle via on_defined? callback

Returns:

  • (Boolean)


49
50
51
52
53
# File 'lib/rubocop/cop/legion/helper_migration/logging_guard.rb', line 49

def on_defined?(node)
  return false unless legion_logging_defined?(node)

  add_offense(node, message: MSG_DEFINED)
end

#on_send(node) ⇒ Object



40
41
42
43
44
45
46
# File 'lib/rubocop/cop/legion/helper_migration/logging_guard.rb', line 40

def on_send(node)
  old_logging_respond_to?(node) do |method_name|
    next unless OLD_METHODS.include?(method_name)

    add_offense(node, message: format(MSG_RESPOND_TO, method: method_name))
  end
end