Skip to content

Commit d8d2ce8

Browse files
authored
Merge pull request #935 from mockdeep/rf-find_in_scope
Deduplicate logic in ExampleGroup
2 parents 96af8f7 + c52bb81 commit d8d2ce8

File tree

1 file changed

+21
-49
lines changed

1 file changed

+21
-49
lines changed

lib/rubocop/rspec/example_group.rb

Lines changed: 21 additions & 49 deletions
Original file line numberDiff line numberDiff line change
@@ -14,72 +14,44 @@ class ExampleGroup < Concept
1414
ExampleGroups::ALL + SharedGroups::ALL + Includes::ALL
1515
).block_pattern
1616

17+
def lets
18+
find_all_in_scope(node, :let?)
19+
end
20+
1721
def subjects
18-
subjects_in_scope(node)
22+
find_all_in_scope(node, :subject?)
1923
end
2024

2125
def examples
22-
examples_in_scope(node).map(&Example.public_method(:new))
26+
find_all_in_scope(node, :example?).map(&Example.public_method(:new))
2327
end
2428

2529
def hooks
26-
hooks_in_scope(node).map(&Hook.public_method(:new))
30+
find_all_in_scope(node, :hook?).map(&Hook.public_method(:new))
2731
end
2832

2933
private
3034

31-
def subjects_in_scope(node)
32-
node.each_child_node.flat_map do |child|
33-
find_subjects(child)
34-
end
35-
end
36-
37-
def find_subjects(node)
38-
return [] if scope_change?(node)
39-
40-
if subject?(node)
41-
[node]
42-
else
43-
subjects_in_scope(node)
44-
end
45-
end
46-
47-
def hooks_in_scope(node)
48-
node.each_child_node.flat_map do |child|
49-
find_hooks(child)
50-
end
51-
end
52-
53-
def find_hooks(node)
54-
return [] if scope_change?(node) || example?(node)
55-
56-
if hook?(node)
57-
[node]
58-
else
59-
hooks_in_scope(node)
60-
end
61-
end
62-
63-
def examples_in_scope(node, &blk)
64-
node.each_child_node.flat_map do |child|
65-
find_examples(child, &blk)
66-
end
67-
end
68-
69-
# Recursively search for examples within the current scope
35+
# Recursively search for predicate within the current scope
7036
#
71-
# Searches node for examples and halts when a scope change is detected
37+
# Searches node and halts when a scope change is detected
7238
#
73-
# @param node [RuboCop::Node] node to recursively search for examples
39+
# @param node [RuboCop::Node] node to recursively search
7440
#
75-
# @return [Array<RuboCop::Node>] discovered example nodes
76-
def find_examples(node)
77-
return [] if scope_change?(node)
41+
# @return [Array<RuboCop::Node>] discovered nodes
42+
def find_all_in_scope(node, predicate)
43+
node.each_child_node.flat_map do |child|
44+
find_all(child, predicate)
45+
end
46+
end
7847

79-
if example?(node)
48+
def find_all(node, predicate)
49+
if public_send(predicate, node)
8050
[node]
51+
elsif scope_change?(node) || example?(node)
52+
[]
8153
else
82-
examples_in_scope(node)
54+
find_all_in_scope(node, predicate)
8355
end
8456
end
8557
end

0 commit comments

Comments
 (0)