forked from rubocop/rubocop
-
Notifications
You must be signed in to change notification settings - Fork 0
/
struct_inheritance.rb
40 lines (36 loc) · 1.01 KB
/
struct_inheritance.rb
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
# frozen_string_literal: true
module RuboCop
module Cop
module Style
# This cop checks for inheritance from Struct.new.
#
# @example
# # bad
# class Person < Struct.new(:first_name, :last_name)
# def age
# 42
# end
# end
#
# # good
# Person = Struct.new(:first_name, :last_name) do
# def age
# 42
# end
# end
class StructInheritance < Cop
MSG = "Don't extend an instance initialized by `Struct.new`. " \
'Use a block to customize the struct.'.freeze
def on_class(node)
_name, superclass, _body = *node
return unless struct_constructor?(superclass)
add_offense(node, location: superclass.source_range)
end
def_node_matcher :struct_constructor?, <<-PATTERN
{(send (const nil? :Struct) :new ...)
(block (send (const nil? :Struct) :new ...) ...)}
PATTERN
end
end
end
end