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

Add branches method for AST::CaseMatchNode #192

Merged
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.
Jump to
Jump to file
Failed to load files.
Diff view
Diff view
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