diff --git a/changelog/new_make_rubocop_ast_if_node_support_then_predicate.md b/changelog/new_make_rubocop_ast_if_node_support_then_predicate.md new file mode 100644 index 000000000..142bdb233 --- /dev/null +++ b/changelog/new_make_rubocop_ast_if_node_support_then_predicate.md @@ -0,0 +1 @@ +* [#341](https://github.com/rubocop/rubocop-ast/pull/341): Make `RuboCop::AST::IfNode` support `then?`. ([@koic][]) diff --git a/lib/rubocop/ast/node/if_node.rb b/lib/rubocop/ast/node/if_node.rb index 3bd4a1192..a567de8bb 100644 --- a/lib/rubocop/ast/node/if_node.rb +++ b/lib/rubocop/ast/node/if_node.rb @@ -25,6 +25,13 @@ def unless? keyword == 'unless' end + # Checks whether the `if` node has an `then` clause. + # + # @return [Boolean] whether the node has an `then` clause + def then? + loc_is?(:begin, 'then') + end + # Checks whether the `if` is an `elsif`. Parser handles these by nesting # `if` nodes in the `else` branch. # diff --git a/spec/rubocop/ast/if_node_spec.rb b/spec/rubocop/ast/if_node_spec.rb index 3876f87b5..9ab5344b0 100644 --- a/spec/rubocop/ast/if_node_spec.rb +++ b/spec/rubocop/ast/if_node_spec.rb @@ -124,6 +124,32 @@ end end + describe '#then?' do + context 'with `then` keyword' do + let(:source) do + <<~SOURCE + if foo? then + 1 + end + SOURCE + end + + it { is_expected.to be_then } + end + + context 'without `then` keyword' do + let(:source) do + <<~SOURCE + if foo? + 1 + end + SOURCE + end + + it { is_expected.not_to be_then } + end + end + describe '#elsif?' do context 'with an elsif statement' do let(:source) do