Skip to content

Commit

Permalink
Fix IfNode#branches to return both branches when called on ternary …
Browse files Browse the repository at this point in the history
…conditional
  • Loading branch information
fatkodima authored and marcandre committed Nov 4, 2020
1 parent f20e85f commit 94a8f87
Show file tree
Hide file tree
Showing 3 changed files with 24 additions and 10 deletions.
4 changes: 4 additions & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,10 @@

* [#144](https://github.com/rubocop-hq/rubocop-ast/pull/144): NodePattern: allow method calls on constants. ([@marcandre][])

### Bug fixes

* [#146](https://github.com/rubocop-hq/rubocop-ast/pull/146): Fix `IfNode#branches` to return both branches when called on ternary conditional. ([@fatkodima][])

## 1.0.1 (2020-10-23)

### Bug fixes
Expand Down
23 changes: 13 additions & 10 deletions lib/rubocop/ast/node/if_node.rb
Original file line number Diff line number Diff line change
Expand Up @@ -145,16 +145,19 @@ def node_parts
#
# @return [Array<Node>] an array of branch nodes
def branches
branches = [if_branch]

return branches unless else?

other_branches = if elsif_conditional?
else_branch.branches
else
[else_branch]
end
branches.concat(other_branches)
if ternary?
[if_branch, else_branch]
elsif !else?
[if_branch]
else
branches = [if_branch]
other_branches = if elsif_conditional?
else_branch.branches
else
[else_branch]
end
branches.concat(other_branches)
end
end

# @deprecated Use `branches.each`
Expand Down
7 changes: 7 additions & 0 deletions spec/rubocop/ast/if_node_spec.rb
Original file line number Diff line number Diff line change
Expand Up @@ -434,6 +434,13 @@
it { expect(if_node.branches).to all(be_literal) }
end

context 'with a ternary operator' do
let(:source) { 'foo? ? :foo : 42' }

it { expect(if_node.branches.size).to eq(2) }
it { expect(if_node.branches).to all(be_literal) }
end

context 'with an unless statement' do
let(:source) { 'unless foo?; :bar; end' }

Expand Down

0 comments on commit 94a8f87

Please sign in to comment.