Class: RuboCop::Cop::Sorbet::MultipleTEnumValues

Inherits:
Base
  • Object
show all
Includes:
TEnum
Defined in:
lib/rubocop/cop/sorbet/t_enum/multiple_t_enum_values.rb

Overview

Disallow creating a ‘T::Enum` with less than two values.

Examples:


# bad
class ErrorMessages < T::Enum
  enums do
    ServerError = new("There was a server error.")
  end
end

# good
class ErrorMessages < T::Enum
  enums do
    ServerError = new("There was a server error.")
    NotFound = new("The resource was not found.")
  end
end

Constant Summary collapse

MSG =
"`T::Enum` should have at least two values."

Instance Method Summary collapse

Methods included from TEnum

#after_class, #initialize, #t_enum?

Instance Method Details

#enums_block?(node) ⇒ Object



30
31
32
# File 'lib/rubocop/cop/sorbet/t_enum/multiple_t_enum_values.rb', line 30

def_node_matcher :enums_block?, <<~PATTERN
  (block (send nil? :enums) ...)
PATTERN

#on_block(node) ⇒ Object

rubocop:disable InternalAffairs/NumblockHandler



40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
# File 'lib/rubocop/cop/sorbet/t_enum/multiple_t_enum_values.rb', line 40

def on_block(node) # rubocop:disable InternalAffairs/NumblockHandler
  return unless in_t_enum_class?
  return unless enums_block?(node)

  scope = @scopes.last

  if node.body.nil?
    add_offense(scope)
    return
  end

  begin_node = node.children.find(&:begin_type?)

  num_casgn_nodes = (begin_node || node).children.count(&:casgn_type?)
  add_offense(scope) if num_casgn_nodes < 2
end

#on_class(node) ⇒ Object



34
35
36
37
38
# File 'lib/rubocop/cop/sorbet/t_enum/multiple_t_enum_values.rb', line 34

def on_class(node)
  super

  add_offense(node) if t_enum?(node) && node.body.nil?
end