diff --git a/CHANGELOG.md b/CHANGELOG.md index 396098f2a..969380676 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -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 diff --git a/lib/rubocop/ast/node/if_node.rb b/lib/rubocop/ast/node/if_node.rb index 5eaea2e8d..9eeaa233b 100644 --- a/lib/rubocop/ast/node/if_node.rb +++ b/lib/rubocop/ast/node/if_node.rb @@ -145,16 +145,19 @@ def node_parts # # @return [Array] 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` diff --git a/spec/rubocop/ast/if_node_spec.rb b/spec/rubocop/ast/if_node_spec.rb index 50183dfbe..ab2bc4fb3 100644 --- a/spec/rubocop/ast/if_node_spec.rb +++ b/spec/rubocop/ast/if_node_spec.rb @@ -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' }