Skip to content

Commit

Permalink
Add branches method for AST::CaseMatchNode
Browse files Browse the repository at this point in the history
This PR adds `branches` method for `AST::CaseMatchNode`.

This makes a method similar to `AST::CaseNode#branches` available
in `AST::CaseMatchNode`.
After this, I will be developing with this API on RuboCop.
  • Loading branch information
koic authored and marcandre committed Jul 14, 2021
1 parent 0925664 commit 0cbbac4
Show file tree
Hide file tree
Showing 3 changed files with 59 additions and 0 deletions.
1 change: 1 addition & 0 deletions changelog/add_branches_method_for_ast_case_match_node.md
@@ -0,0 +1 @@
* [#192](https://github.com/rubocop/rubocop-ast/pull/192): Add `branches` method for `AST::CaseMatchNode`. ([@koic][])
13 changes: 13 additions & 0 deletions lib/rubocop/ast/node/case_match_node.rb
Expand Up @@ -31,6 +31,19 @@ def in_pattern_branches
node_parts[1...-1]
end

# Returns an array of all the when branches in the `case` statement.
#
# @return [Array<Node, nil>] an array of the bodies of the `in` branches
# and the `else` (if any). Note that these bodies could be nil.
def branches
bodies = in_pattern_branches.map(&:body)
if else?
# `empty-else` node sets nil because it has no body.
else_branch.empty_else_type? ? bodies.push(nil) : bodies.push(else_branch)
end
bodies
end

# Returns the else branch of the `case` statement, if any.
#
# @return [Node] the else branch node of the `case` statement
Expand Down
45 changes: 45 additions & 0 deletions spec/rubocop/ast/case_match_node_spec.rb
Expand Up @@ -127,5 +127,50 @@
end
end
end

describe '#branches' do
context 'when there is an else' do
context 'with else body' do
let(:source) { <<~RUBY }
case pattern
in :foo then # do nothing
in :bar then 42
else 'hello'
end
RUBY

it 'returns all the bodies' do
expect(case_match_node.branches).to match [nil, be_int_type, be_str_type]
end
end

context 'with empty else' do
let(:source) { <<~RUBY }
case pattern
in :foo then # do nothing
in :bar then 42
else # do nothing
end
RUBY

it 'returns all the bodies' do
expect(case_match_node.branches).to match [nil, be_int_type, nil]
end
end
end

context 'when there is no else keyword' do
let(:source) { <<~RUBY }
case pattern
in :foo then # do nothing
in :bar then 42
end
RUBY

it 'returns only then when bodies' do
expect(case_match_node.branches).to match [nil, be_int_type]
end
end
end
end
end

0 comments on commit 0cbbac4

Please sign in to comment.