forked from rubocop/rubocop
-
Notifications
You must be signed in to change notification settings - Fork 0
/
useless_method_definition.rb
87 lines (76 loc) · 2.16 KB
/
useless_method_definition.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
# frozen_string_literal: true
module RuboCop
module Cop
module Lint
# This cop checks for useless method definitions, specifically: empty constructors
# and methods just delegating to `super`.
#
# This cop is marked as unsafe as it can trigger false positives for cases when
# an empty constructor just overrides the parent constructor, which is bad anyway.
#
# @example
# # bad
# def initialize
# end
#
# def method
# super
# end
#
# # good - with default arguments
# def initialize(x = Object.new)
# super
# end
#
# # good
# def initialize
# initialize_internals
# end
#
# def method
# super
# do_something_else
# end
#
# @example AllowComments: true (default)
# # good
# def initialize
# # Comment.
# end
#
# @example AllowComments: false
# # bad
# def initialize
# # Comment.
# end
#
class UselessMethodDefinition < Base
extend AutoCorrector
MSG = 'Useless method definition detected.'
def on_def(node)
return if optional_args?(node)
return unless (constructor?(node) && empty_constructor?(node)) ||
delegating?(node.body, node)
add_offense(node) { |corrector| corrector.remove(node) }
end
alias on_defs on_def
private
def optional_args?(node)
node.arguments.any? { |arg| arg.optarg_type? || arg.kwoptarg_type? }
end
def empty_constructor?(node)
return false if node.body
return false if cop_config['AllowComments'] && comment_lines?(node)
true
end
def constructor?(node)
node.def_type? && node.method?(:initialize)
end
def delegating?(node, def_node)
return false unless node&.super_type? || node&.zsuper_type?
!node.arguments? || node.arguments.map(&:source) == def_node.arguments.map(&:source)
end
end
end
end
end