Class: RuboCop::Cop::Legion::Extension::SettingsKeyMethod

Inherits:
Base
  • Object
show all
Extended by:
AutoCorrector
Defined in:
lib/rubocop/cop/legion/extension/settings_key_method.rb

Overview

Detects calls to ‘Legion::Settings.key?(:foo)` which will raise `NoMethodError` because `Legion::Settings` is a module, not a Hash. Auto-corrects to `!Legion::Settings.nil?`.

Examples:

# bad
Legion::Settings.key?(:foo)

# good
!Legion::Settings[:foo].nil?

Constant Summary collapse

RESTRICT_ON_SEND =
%i[key?].freeze
MSG =
'`Legion::Settings` has no `key?` method. ' \
'Use `!Legion::Settings[:%<key>s].nil?` instead.'

Instance Method Summary collapse

Instance Method Details

#legion_settings_key?(node) ⇒ Object



26
27
28
29
30
31
# File 'lib/rubocop/cop/legion/extension/settings_key_method.rb', line 26

def_node_matcher :legion_settings_key?, <<~PATTERN
  (send
    (const (const nil? :Legion) :Settings)
    :key?
    $_)
PATTERN

#on_send(node) ⇒ Object



33
34
35
36
37
38
39
40
41
42
43
44
# File 'lib/rubocop/cop/legion/extension/settings_key_method.rb', line 33

def on_send(node)
  key_node = legion_settings_key?(node)
  return unless key_node

  key_str = source_for_key(key_node)
  message = format(MSG, key: key_str)

  add_offense(node, message: message) do |corrector|
    replacement = "!Legion::Settings[:#{key_str}].nil?"
    corrector.replace(node, replacement)
  end
end