Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Fix IfNode#branches to return both branches when called on ternary conditional #146

Merged
merged 1 commit into from
Nov 4, 2020
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
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) }
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

FYI, I think you can do both in a single expectaction to match [be_literal, be_literal]

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I just stick to the existing codestyle and replicated the nearest similar example 😄

end

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

Expand Down