class RuboCop::Cop::Lint::MissingSuper

Checks for the presence of constructors and lifecycle callbacks without calls to `super`.

This cop does not consider `method_missing` (and `respond_to_missing?`) because in some cases it makes sense to overtake what is considered a missing method. In other cases, the theoretical ideal handling could be challenging or verbose for no actual gain.

@example

# bad
class Employee < Person
  def initialize(name, salary)
    @salary = salary
  end
end

# good
class Employee < Person
  def initialize(name, salary)
    super(name)
    @salary = salary
  end
end

# bad
class Parent
  def self.inherited(base)
    do_something
  end
end

# good
class Parent
  def self.inherited(base)
    super
    do_something
  end
end

Constants

CALLBACKS
CALLBACK_MSG
CLASS_LIFECYCLE_CALLBACKS
CONSTRUCTOR_MSG
METHOD_LIFECYCLE_CALLBACKS
STATELESS_CLASSES

Public Instance Methods

on_def(node) click to toggle source
# File lib/rubocop/cop/lint/missing_super.rb, line 58
def on_def(node)
  return unless offender?(node)

  if node.method?(:initialize) && inside_class_with_stateful_parent?(node)
    add_offense(node, message: CONSTRUCTOR_MSG)
  elsif callback_method_def?(node)
    add_offense(node, message: CALLBACK_MSG)
  end
end
on_defs(node) click to toggle source
# File lib/rubocop/cop/lint/missing_super.rb, line 68
def on_defs(node)
  return if !callback_method_def?(node) || contains_super?(node)

  add_offense(node, message: CALLBACK_MSG)
end

Private Instance Methods

callback_method_def?(node) click to toggle source
# File lib/rubocop/cop/lint/missing_super.rb, line 80
def callback_method_def?(node)
  return unless CALLBACKS.include?(node.method_name)

  node.each_ancestor(:class, :sclass, :module).first
end
contains_super?(node) click to toggle source
# File lib/rubocop/cop/lint/missing_super.rb, line 86
def contains_super?(node)
  node.each_descendant(:super, :zsuper).any?
end
inside_class_with_stateful_parent?(node) click to toggle source
# File lib/rubocop/cop/lint/missing_super.rb, line 90
def inside_class_with_stateful_parent?(node)
  class_node = node.each_ancestor(:class).first
  class_node&.parent_class && !stateless_class?(class_node.parent_class)
end
offender?(node) click to toggle source
# File lib/rubocop/cop/lint/missing_super.rb, line 76
def offender?(node)
  (node.method?(:initialize) || callback_method_def?(node)) && !contains_super?(node)
end
stateless_class?(node) click to toggle source
# File lib/rubocop/cop/lint/missing_super.rb, line 95
def stateless_class?(node)
  STATELESS_CLASSES.include?(node.const_name)
end