Skip to content

Commit

Permalink
Make SendNode#macro? aware of struct constructor
Browse files Browse the repository at this point in the history
This PR makes `SendNode#macro?` and `RuboCop::AST::Node#class_constructor?`
aware of struct constructor and `RuboCop::AST::Node#struct_constructor?`
is deprecated.

Like class constructor, struct constructor will be recognized as a
macro and will be awakened in the following `private` modifier:

```ruby
Foo = Struct.new(:foo) do
  private
    def private_foo
      foo
    end
end
```

With this change, this PR aims to resolve the following issue.
rubocop/rubocop#8919
  • Loading branch information
koic authored and marcandre committed Oct 23, 2020
1 parent 395c5ca commit 827c1ed
Show file tree
Hide file tree
Showing 3 changed files with 18 additions and 2 deletions.
4 changes: 4 additions & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,10 @@

## master (unreleased)

### Bug fixes

* [#141](https://github.com/rubocop-hq/rubocop-ast/pull/141): Make `SendNode#macro?` and `RuboCop::AST::Node#class_constructor?` aware of struct constructor and `RuboCop::AST::Node#struct_constructor?` is deprecated. ([@koic][])

## 1.0.0 (2020-10-21)

### Changes
Expand Down
5 changes: 3 additions & 2 deletions lib/rubocop/ast/node.rb
Original file line number Diff line number Diff line change
Expand Up @@ -484,10 +484,11 @@ def guard_clause?
def_node_matcher :global_const?, '(const {nil? cbase} %1)'

def_node_matcher :class_constructor?, <<~PATTERN
{ (send #global_const?({:Class :Module}) :new ...)
(block (send #global_const?({:Class :Module}) :new ...) ...)}
{ (send #global_const?({:Class :Module :Struct}) :new ...)
(block (send #global_const?({:Class :Module :Struct}) :new ...) ...)}
PATTERN

# @deprecated Use `:class_constructor?`
def_node_matcher :struct_constructor?, <<~PATTERN
(block (send #global_const?(:Struct) :new ...) _ $_)
PATTERN
Expand Down
11 changes: 11 additions & 0 deletions spec/rubocop/ast/send_node_spec.rb
Original file line number Diff line number Diff line change
Expand Up @@ -242,6 +242,17 @@ module Foo
it { expect(send_node).to be_macro }
end

context 'when parent is a struct constructor' do
let(:source) do
['Foo = Struct.new do',
'>>bar :baz<<',
' bar :qux',
'end'].join("\n")
end

it { expect(send_node).to be_macro }
end

context 'when parent is a singleton class' do
let(:source) do
['class << self',
Expand Down

0 comments on commit 827c1ed

Please sign in to comment.