/
missing_super.rb
99 lines (84 loc) · 2.77 KB
/
missing_super.rb
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
# frozen_string_literal: true
module RuboCop
module Cop
module Lint
# This cop checks for the presence of constructors and lifecycle callbacks
# without calls to `super`.
#
# @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
#
class MissingSuper < Base
CONSTRUCTOR_MSG = 'Call `super` to initialize state of the parent class.'
CALLBACK_MSG = 'Call `super` to invoke callback defined in the parent class.'
STATELESS_CLASSES = %w[BasicObject Object].freeze
OBJECT_LIFECYCLE_CALLBACKS = %i[method_missing respond_to_missing?].freeze
CLASS_LIFECYCLE_CALLBACKS = %i[inherited].freeze
MODULE_LIFECYCLE_CALLBACKS = %i[included extended prepended].freeze
def on_def(node)
return unless offender?(node)
if node.method?(:initialize)
add_offense(node, message: CONSTRUCTOR_MSG) if inside_class_with_stateful_parent?(node)
elsif callback_method_def?(node)
add_offense(node, message: CALLBACK_MSG)
end
end
def on_defs(node)
return if !callback_method_def?(node) || contains_super?(node)
add_offense(node, message: CALLBACK_MSG)
end
private
def offender?(node)
(node.method?(:initialize) || callback_method_def?(node)) && !contains_super?(node)
end
def callback_method_def?(node)
method_name = node.method_name
if OBJECT_LIFECYCLE_CALLBACKS.include?(method_name) ||
CLASS_LIFECYCLE_CALLBACKS.include?(method_name)
node.each_ancestor(:class, :sclass, :module).first
elsif MODULE_LIFECYCLE_CALLBACKS.include?(method_name)
node.each_ancestor(:module).first
end
end
def contains_super?(node)
node.each_descendant(:super, :zsuper).any?
end
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
def stateless_class?(node)
STATELESS_CLASSES.include?(node.const_name)
end
end
end
end
end