Class: RuboCop::Cop::Sorbet::StructPropName

Inherits:
Base
  • Object
show all
Includes:
AllowedPattern, ConfigurableNaming, ForbiddenIdentifiers, ForbiddenPattern
Defined in:
lib/rubocop/cop/sorbet/struct_prop_name.rb

Overview

Checks that T::Struct property names use the configured style. The supported styles and name filters match Naming/MethodName.

Examples:

EnforcedStyle: snake_case (default)

# bad
class User < T::Struct
  const :firstName, String
  prop :lastName, String
end

# good
class User < T::Struct
  const :first_name, String
  prop :last_name, String
end

EnforcedStyle: camelCase

# bad
class User < T::Struct
  const :first_name, String
  prop :last_name, String
end

# good
class User < T::Struct
  const :firstName, String
  prop :lastName, String
end

AllowedPatterns: ['Alegacy[A-Z]']

# good
class User < T::Struct
  const :legacyName, String
end

ForbiddenIdentifiers: ['legacy_name']

# bad
class User < T::Struct
  const :legacy_name, String
end

ForbiddenPatterns: ['_v1\z']

# bad
class User < T::Struct
  const :name_v1, String
end

Constant Summary collapse

MSG =
"Use %<style>s for T::Struct property names."
MSG_FORBIDDEN =
"`%<identifier>s` is forbidden, use another property name instead."
RESTRICT_ON_SEND =
[:const, :prop].freeze

Instance Method Summary collapse

Instance Method Details

#on_send(node) ⇒ Object



68
69
70
71
72
73
74
75
76
77
78
79
80
81
# File 'lib/rubocop/cop/sorbet/struct_prop_name.rb', line 68

def on_send(node)
  name_node = node.first_argument
  receiver = node.receiver
  return unless (receiver.nil? || receiver.self_type?) && name_node&.sym_type? && within_t_struct?(node)

  name = name_node.value
  return if matches_allowed_pattern?(name)

  if forbidden_name?(name)
    add_offense(name_node, message: format(MSG_FORBIDDEN, identifier: name))
  else
    check_name(node, name, name_node)
  end
end

#t_struct?(node) ⇒ Object



64
65
66
# File 'lib/rubocop/cop/sorbet/struct_prop_name.rb', line 64

def_node_matcher :t_struct?, <<~PATTERN
  (const (const {nil? cbase} :T) {:Struct :ImmutableStruct :InexactStruct})
PATTERN