Skip to content

Commit

Permalink
Add EnsureNode#rescue_node.
Browse files Browse the repository at this point in the history
  • Loading branch information
dvandersluis committed Nov 8, 2024
1 parent b310f30 commit b45bb9f
Show file tree
Hide file tree
Showing 3 changed files with 54 additions and 0 deletions.
7 changes: 7 additions & 0 deletions lib/rubocop/ast/node/ensure_node.rb
Original file line number Diff line number Diff line change
Expand Up @@ -13,6 +13,13 @@ def body
node_parts[1]
end

# Returns the `rescue` node of the `ensure`, if present.
#
# @return [Node, nil] The `rescue` node.
def rescue_node
node_parts[0] if node_parts[0].rescue_type?
end

# Checks whether this node body is a void context.
# Always `true` for `ensure`.
#
Expand Down
34 changes: 34 additions & 0 deletions spec/rubocop/ast/ensure_node_spec.rb
Original file line number Diff line number Diff line change
Expand Up @@ -15,6 +15,40 @@
it { expect(ensure_node.body).to be_sym_type }
end

describe '#rescue_node' do
subject(:rescue_node) { ensure_node.rescue_node }

context 'when there is no `rescue` node' do
let(:source) do
<<~RUBY
begin
beginbody
ensure
ensurebody
end
RUBY
end

it { is_expected.to be_nil }
end

context 'when there is a `rescue` node' do
let(:source) do
<<~RUBY
begin
beginbody
rescue
rescuebody
ensure
ensurebody
end
RUBY
end

it { is_expected.to be_a(RuboCop::AST::RescueNode) }
end
end

describe '#void_context?' do
let(:source) { 'begin; beginbody; ensure; ensurebody; end' }

Expand Down
13 changes: 13 additions & 0 deletions spec/rubocop/ast/rescue_node_spec.rb
Original file line number Diff line number Diff line change
Expand Up @@ -24,6 +24,19 @@
RUBY

it { expect(rescue_node.body).to be_send_type }

context 'with multiple lines in body' do
let(:source) { <<~RUBY }
begin
foo
bar
rescue => e
baz
end
RUBY

it { expect(rescue_node.body).to be_begin_type }
end
end

describe '#resbody_branches' do
Expand Down

0 comments on commit b45bb9f

Please sign in to comment.