Class: RuboCop::Cop::Lint::ToEnumArguments

Inherits:
Base
  • Object
show all
Defined in:
lib/rubocop/cop/lint/to_enum_arguments.rb

Overview

This cop ensures that `to_enum`/`enum_for`, called for the current method, has correct arguments.

Examples:

# bad
def foo(x, y = 1)
  return to_enum(__callee__, x) # `y` is missing
end

# good
def foo(x, y = 1)
  return to_enum(__callee__, x, y)
  # alternatives to `__callee__` are `__method__` and `:foo`
end

Constant Summary collapse

MSG =
'Ensure you correctly provided all the arguments.'
RESTRICT_ON_SEND =
%i[to_enum enum_for].freeze

Instance Attribute Summary

Attributes inherited from Base

#config, #processed_source

Instance Method Summary collapse

Methods inherited from Base

#add_global_offense, #add_offense, autocorrect_incompatible_with, badge, #callbacks_needed, callbacks_needed, #config_to_allow_offenses, #config_to_allow_offenses=, #cop_config, #cop_name, cop_name, department, documentation_url, exclude_from_registry, #excluded_file?, #external_dependency_checksum, inherited, #initialize, joining_forces, lint?, match?, #message, #offenses, #on_investigation_end, #on_new_investigation, #on_other_file, #parse, #ready, #relevant_file?, support_autocorrect?, support_multiple_source?, #target_rails_version, #target_ruby_version

Methods included from ExcludeLimit

#exclude_limit

Methods included from AutocorrectLogic

#autocorrect?, #autocorrect_enabled?, #autocorrect_requested?, #correctable?, #disable_uncorrectable?, #safe_autocorrect?

Methods included from IgnoredNode

#ignore_node, #ignored_node?, #part_of_ignored_node?

Methods included from Util

silence_warnings

Constructor Details

This class inherits a constructor from RuboCop::Cop::Base

Instance Method Details

#enum_conversion_call?(node) ⇒ Object


27
28
29
# File 'lib/rubocop/cop/lint/to_enum_arguments.rb', line 27

def_node_matcher :enum_conversion_call?, <<~PATTERN
  (send {nil? self} {:to_enum :enum_for} $_ $...)
PATTERN

#method_name?(node, name) ⇒ Object


32
33
34
# File 'lib/rubocop/cop/lint/to_enum_arguments.rb', line 32

def_node_matcher :method_name?, <<~PATTERN
  {(send nil? {:__method__ :__callee__}) (sym %1)}
PATTERN

#on_send(node) ⇒ Object


41
42
43
44
45
46
47
48
49
# File 'lib/rubocop/cop/lint/to_enum_arguments.rb', line 41

def on_send(node)
  def_node = node.each_ancestor(:def, :defs).first
  return unless def_node

  enum_conversion_call?(node) do |method_node, arguments|
    add_offense(node) unless method_name?(method_node, def_node.method_name) &&
                             arguments_match?(arguments, def_node)
  end
end

#passing_keyword_arg?(node, name) ⇒ Object


37
38
39
# File 'lib/rubocop/cop/lint/to_enum_arguments.rb', line 37

def_node_matcher :passing_keyword_arg?, <<~PATTERN
  (pair (sym %1) (lvar %1))
PATTERN