diff --git a/changelog/new_add_pattern_method_for_ast_in_pattern_node b/changelog/new_add_pattern_method_for_ast_in_pattern_node new file mode 100644 index 000000000..1a7af2590 --- /dev/null +++ b/changelog/new_add_pattern_method_for_ast_in_pattern_node @@ -0,0 +1 @@ +* [#186](https://github.com/rubocop-hq/rubocop-ast/pull/186): Add `pattern` method for `AST::InPatternNode` node. ([@koic][]) diff --git a/lib/rubocop/ast/node/in_pattern_node.rb b/lib/rubocop/ast/node/in_pattern_node.rb index b1470d99c..cdea7ed46 100644 --- a/lib/rubocop/ast/node/in_pattern_node.rb +++ b/lib/rubocop/ast/node/in_pattern_node.rb @@ -6,6 +6,13 @@ module AST # node when the builder constructs the AST, making its methods available # to all `in` nodes within RuboCop. class InPatternNode < Node + # Returns a node of the pattern in the `in` branch. + # + # @return [Node] a pattern node + def pattern + node_parts.first + end + # Returns the index of the `in` branch within the `case` statement. # # @return [Integer] the index of the `in` branch diff --git a/spec/rubocop/ast/in_pattern_node_spec.rb b/spec/rubocop/ast/in_pattern_node_spec.rb index 0d6261c4d..2daa71a9e 100644 --- a/spec/rubocop/ast/in_pattern_node_spec.rb +++ b/spec/rubocop/ast/in_pattern_node_spec.rb @@ -14,6 +14,78 @@ it { expect(in_pattern_node).to be_a(described_class) } end + describe '#pattern' do + context 'with a value pattern' do + let(:source) do + ['case condition', + 'in 42 then foo', + 'end'].join("\n") + end + + it { expect(in_pattern_node.pattern).to be_int_type } + end + + context 'with a variable pattern' do + let(:source) do + ['case condition', + 'in var then foo', + 'end'].join("\n") + end + + it { expect(in_pattern_node.pattern).to be_match_var_type } + end + + context 'with an alternative pattern' do + let(:source) do + ['case condition', + 'in :foo | :bar | :baz then foo', + 'end'].join("\n") + end + + it { expect(in_pattern_node.pattern).to be_match_alt_type } + end + + context 'with an as pattern' do + let(:source) do + ['case condition', + 'in Integer => var then foo', + 'end'].join("\n") + end + + it { expect(in_pattern_node.pattern).to be_match_as_type } + end + + context 'with an array pattern' do + let(:source) do + ['case condition', + 'in :foo, :bar, :baz then foo', + 'end'].join("\n") + end + + it { expect(in_pattern_node.pattern).to be_array_pattern_type } + end + + context 'with a hash pattern' do + let(:source) do + ['case condition', + 'in foo:, bar:, baz: then foo', + 'end'].join("\n") + end + + it { expect(in_pattern_node.pattern).to be_hash_pattern_type } + end + + context 'with a pin operator', :ruby31 do + let(:source) do + ['case condition', + 'in ^(2 + 2) then foo', + 'end'].join("\n") + end + + it { expect(in_pattern_node.pattern).to be_pin_type } + end + end + describe '#then?' do context 'with a then keyword' do let(:source) do