Class: RuboCop::Cop::InternalAffairs::AssignmentFirst

Inherits:
Base
  • Object
show all
Defined in:
lib/rubocop/cop/internal_affairs/assignment_first.rb

Overview

Check for assignment as the first action in a cop hook.

Examples:

# bad
def on_send(node)
  foo = 1
  do_something
end

# good
def on_send(node)
  do_something
  foo = 1
end

Constant Summary collapse

HOOKS =
%i(
  on_def
  on_defs
  on_send
  on_csend
  on_const
  on_int
  on_class
  on_module
  on_block
  on_begin
  on_kwbegin
  after_int
  after_def
  after_send
  after_csend
  after_class
  after_module
).to_set.freeze
MSG =
"Avoid placing an assignment as the first action in `%{hook}`."

Instance Method Summary collapse

Instance Method Details

#on_def(node) ⇒ Object



43
44
45
46
47
48
49
50
51
52
# File 'lib/rubocop/cop/internal_affairs/assignment_first.rb', line 43

def on_def(node)
  return unless HOOKS.include?(node.method_name)
  return unless node.body

  # Look through a begin node, e.g. look inside parentheses
  first_child = node.body.begin_type? ? node.body.children.first : node.body
  return unless first_child&.assignment?

  add_offense(first_child, message: format(MSG, hook: node.method_name))
end