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

DataInheritance cop similar to StructInheritance #11696

Closed
bdewater opened this issue Mar 13, 2023 · 3 comments · Fixed by #11728
Closed

DataInheritance cop similar to StructInheritance #11696

bdewater opened this issue Mar 13, 2023 · 3 comments · Fixed by #11728

Comments

@bdewater
Copy link
Contributor

bdewater commented Mar 13, 2023

Is your feature request related to a problem? Please describe.

https://github.com/rubocop/rubocop/blob/master/lib/rubocop/cop/style/struct_inheritance.rb exists because using the bad form creates a useless anonymous class (as documented):

irb(main):001:0> class MyStruct < Struct.new(:foo); end
=> nil
irb(main):002:0> MyStruct.ancestors
=> [MyStruct, #<Class:0x0000000105e95790>, Struct, Enumerable, Object, PP::ObjectMixin, Kernel, BasicObject]

Ruby 3.2's Data class has the same issue, so it makes sense to have that cop (or a new cop) detect the same pattern:

irb(main):003:0> class Point < Data.define(:x, :y); end
=> nil
irb(main):004:0> Point.ancestors
=> [Point, #<Class:0x0000000105e9ef70>, Data, Object, PP::ObjectMixin, Kernel, BasicObject]

Describe the solution you'd like

# bad
class Point < Data.define(:x, :y); end

# good
Point = Data.define(:x, :y)

Describe alternatives you've considered

N/A

Additional context

N/A

@ktopolski
Copy link

Hey 👋

If this issue is free for grabs I'd love to work on it! Been using rubocop for years and would love to contribute back to the community 😅

@bdewater
Copy link
Contributor Author

Go for it!

ktopolski pushed a commit to ktopolski/ruby-style-guide that referenced this issue Mar 26, 2023
See also:
* [PR adding new cop for this rule](rubocop/rubocop#11728)
* [Original issue](rubocop/rubocop#11696)
ktopolski pushed a commit to ktopolski/ruby-style-guide that referenced this issue Mar 26, 2023
See also:
* [PR adding new cop for this rule](rubocop/rubocop#11728)
* [Original issue](rubocop/rubocop#11696)
ktopolski pushed a commit to ktopolski/rubocop that referenced this issue Apr 2, 2023
koic added a commit that referenced this issue Apr 3, 2023
@MatheusRich
Copy link

@koic @bdewater I wonder if we should revert this or improve it.

Using inheritance is a very straightforward way to create constants within a class:

class MyClass < Data.define(:foo, :bar)
  A_CONST = 1
end

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Projects
None yet
Development

Successfully merging a pull request may close this issue.

4 participants