Sha256: 5811ad8269c7c4fdcebaa66c8f14468f2ec3da2b09767c617d271cbcc2d0deb3
Contents?: true
Size: 1.61 KB
Versions: 2
Compression:
Stored size: 1.61 KB
Contents
# 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 include RangeHelp MSG = "Don't extend an instance initialized by `Struct.new`. " \ 'Use a block to customize the struct.' def on_class(node) return unless struct_constructor?(node.parent_class) add_offense(node, location: node.parent_class.source_range) end def autocorrect(node) lambda do |corrector| corrector.remove(range_with_surrounding_space(range: node.loc.keyword, newlines: false)) corrector.replace(node.loc.operator, '=') correct_parent(node.parent_class, corrector) end end def_node_matcher :struct_constructor?, <<~PATTERN {(send (const {nil? cbase} :Struct) :new ...) (block (send (const {nil? cbase} :Struct) :new ...) ...)} PATTERN private def correct_parent(parent, corrector) if parent.block_type? corrector.remove(range_with_surrounding_space(range: parent.loc.end, newlines: false)) else corrector.insert_after(parent.loc.expression, ' do') end end end end end end
Version data entries
2 entries across 2 versions & 1 rubygems
Version | Path |
---|---|
rubocop-0.89.1 | lib/rubocop/cop/style/struct_inheritance.rb |
rubocop-0.89.0 | lib/rubocop/cop/style/struct_inheritance.rb |