Class: RuboCop::Cop::Style::RbsInline::StructNewWithBlock

Inherits:
Base
  • Object
show all
Defined in:
lib/rubocop/cop/style/rbs_inline/struct_new_with_block.rb,
sig/rubocop/cop/style/rbs_inline/struct_new_with_block.rbs

Overview

Checks for Struct.new calls with a block.

RBS::Inline does not parse the contents of Struct.new blocks, so any methods defined inside will not be recognized for type checking. Instead, call Struct.new without a block and define additional methods by reopening the class separately.

Examples:

# bad
User = Struct.new(:name, :role) do
  def admin? = role == :admin #: bool
end

# good
User = Struct.new(:name, :role)

class User
  def admin? = role == :admin #: bool
end

Constant Summary collapse

MSG =

Returns:

  • (::String)
"Do not use `Struct.new` with a block. RBS::Inline does not parse block contents, " \
"so methods defined in the block will not be recognized. " \
"Use a separate class definition instead."

Instance Method Summary collapse

Instance Method Details

#on_send(node) ⇒ void

This method returns an undefined value.

Parameters:

  • node (RuboCop::AST::SendNode)


33
34
35
36
37
38
39
40
# File 'lib/rubocop/cop/style/rbs_inline/struct_new_with_block.rb', line 33

def on_send(node) #: void
  return unless struct_like_class?(node)

  block_node = node.parent
  return unless block_node&.block_type?

  add_offense(node)
end

#struct_like_class?(node) ⇒ Boolean

Parameters:

  • node (RuboCop::AST::SendNode)

Returns:

  • (Boolean)


45
46
47
48
49
# File 'lib/rubocop/cop/style/rbs_inline/struct_new_with_block.rb', line 45

def struct_like_class?(node) #: bool
  return false unless node.method_name == :new

  (r = node.receiver).is_a?(RuboCop::AST::ConstNode) && r.short_name == :Struct
end