Skip to content

Commit

Permalink
Make Node#class_construcor? aware of Ruby 3.2's Data.define
Browse files Browse the repository at this point in the history
Ruby 3.2 introduced immutable `Data.define`. Since this is similar to `Struct.new`,
`Node#class_constructor` will handle it in the same way.
  • Loading branch information
koic authored and marcandre committed Feb 11, 2023
1 parent 8edeebf commit 95bb3c0
Show file tree
Hide file tree
Showing 3 changed files with 35 additions and 2 deletions.
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
* [#255](https://github.com/rubocop/rubocop-ast/pull/255): Make `Node#class_constructor?` aware of Ruby 3.2's `Data.define`. ([@koic][])
10 changes: 8 additions & 2 deletions lib/rubocop/ast/node.rb
Original file line number Diff line number Diff line change
Expand Up @@ -510,8 +510,14 @@ def guard_clause?

# @!method class_constructor?(node = self)
def_node_matcher :class_constructor?, <<~PATTERN
{ (send #global_const?({:Class :Module :Struct}) :new ...)
(block (send #global_const?({:Class :Module :Struct}) :new ...) ...)}
{
(send #global_const?({:Class :Module :Struct}) :new ...)
(send #global_const?(:Data) :define ...)
(block {
(send #global_const?({:Class :Module :Struct}) :new ...)
(send #global_const?(:Data) :define ...)
} ...)
}
PATTERN

# @deprecated Use `:class_constructor?`
Expand Down
26 changes: 26 additions & 0 deletions spec/rubocop/ast/node_spec.rb
Original file line number Diff line number Diff line change
Expand Up @@ -423,6 +423,32 @@ def used?
expect(node).to be_class_constructor
end
end

context 'using Ruby >= 3.2', :ruby32 do
context 'Data definition with a block' do
let(:src) { 'Data.define(:foo, :bar) { def a = 42 }' }

it 'matches' do
expect(node).to be_class_constructor
end
end

context 'Data definition without block' do
let(:src) { 'Data.define(:foo, :bar)' }

it 'matches' do
expect(node).to be_class_constructor
end
end

context '::Data' do
let(:src) { '::Data.define(:foo, :bar) { def a = 42 }' }

it 'matches' do
expect(node).to be_class_constructor
end
end
end
end

describe '#struct_constructor?' do
Expand Down

0 comments on commit 95bb3c0

Please sign in to comment.