This repository has been archived by the owner on Feb 19, 2024. It is now read-only.
forked from rubocop/rubocop
/
nested_method_definition.rb
104 lines (95 loc) · 2.45 KB
/
nested_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
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
# frozen_string_literal: true
module RuboCop
module Cop
module Lint
# This cop checks for nested method definitions.
#
# @example
#
# # bad
#
# # `bar` definition actually produces methods in the same scope
# # as the outer `foo` method. Furthermore, the `bar` method
# # will be redefined every time `foo` is invoked.
# def foo
# def bar
# end
# end
#
# @example
#
# # good
#
# def foo
# bar = -> { puts 'hello' }
# bar.call
# end
#
# @example
#
# # good
#
# def foo
# self.class.class_eval do
# def bar
# end
# end
# end
#
# def foo
# self.class.module_exec do
# def bar
# end
# end
# end
#
# @example
#
# # good
#
# def foo
# class << self
# def bar
# end
# end
# end
class NestedMethodDefinition < Cop
MSG = 'Method definitions must not be nested. ' \
'Use `lambda` instead.'
def on_def(node)
find_nested_defs(node) do |nested_def_node|
add_offense(nested_def_node)
end
end
alias on_defs on_def
private
def find_nested_defs(node, &block)
node.each_child_node do |child|
if child.def_type?
yield child
elsif child.defs_type?
subject, = *child
next if subject.lvar_type?
yield child
elsif !scoping_method_call?(child)
find_nested_defs(child, &block)
end
end
end
def scoping_method_call?(child)
eval_call?(child) || exec_call?(child) || child.sclass_type? ||
class_or_module_or_struct_new_call?(child)
end
def_node_matcher :eval_call?, <<~PATTERN
(block (send _ {:instance_eval :class_eval :module_eval} ...) ...)
PATTERN
def_node_matcher :exec_call?, <<~PATTERN
(block (send _ {:instance_exec :class_exec :module_exec} ...) ...)
PATTERN
def_node_matcher :class_or_module_or_struct_new_call?, <<~PATTERN
(block (send (const {nil? cbase} {:Class :Module :Struct}) :new ...) ...)
PATTERN
end
end
end
end