Skip to content

Commit b45bb9f

Browse files
committed
Add EnsureNode#rescue_node.
1 parent b310f30 commit b45bb9f

File tree

3 files changed

+54
-0
lines changed

3 files changed

+54
-0
lines changed

lib/rubocop/ast/node/ensure_node.rb

Lines changed: 7 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -13,6 +13,13 @@ def body
1313
node_parts[1]
1414
end
1515

16+
# Returns the `rescue` node of the `ensure`, if present.
17+
#
18+
# @return [Node, nil] The `rescue` node.
19+
def rescue_node
20+
node_parts[0] if node_parts[0].rescue_type?
21+
end
22+
1623
# Checks whether this node body is a void context.
1724
# Always `true` for `ensure`.
1825
#

spec/rubocop/ast/ensure_node_spec.rb

Lines changed: 34 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -15,6 +15,40 @@
1515
it { expect(ensure_node.body).to be_sym_type }
1616
end
1717

18+
describe '#rescue_node' do
19+
subject(:rescue_node) { ensure_node.rescue_node }
20+
21+
context 'when there is no `rescue` node' do
22+
let(:source) do
23+
<<~RUBY
24+
begin
25+
beginbody
26+
ensure
27+
ensurebody
28+
end
29+
RUBY
30+
end
31+
32+
it { is_expected.to be_nil }
33+
end
34+
35+
context 'when there is a `rescue` node' do
36+
let(:source) do
37+
<<~RUBY
38+
begin
39+
beginbody
40+
rescue
41+
rescuebody
42+
ensure
43+
ensurebody
44+
end
45+
RUBY
46+
end
47+
48+
it { is_expected.to be_a(RuboCop::AST::RescueNode) }
49+
end
50+
end
51+
1852
describe '#void_context?' do
1953
let(:source) { 'begin; beginbody; ensure; ensurebody; end' }
2054

spec/rubocop/ast/rescue_node_spec.rb

Lines changed: 13 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -24,6 +24,19 @@
2424
RUBY
2525

2626
it { expect(rescue_node.body).to be_send_type }
27+
28+
context 'with multiple lines in body' do
29+
let(:source) { <<~RUBY }
30+
begin
31+
foo
32+
bar
33+
rescue => e
34+
baz
35+
end
36+
RUBY
37+
38+
it { expect(rescue_node.body).to be_begin_type }
39+
end
2740
end
2841

2942
describe '#resbody_branches' do

0 commit comments

Comments
 (0)