Class: RuboCop::Cop::Style::RbsInline::DataDefineWithBlock

Inherits:
Base
  • Object
show all
Includes:
ASTUtils, DataClassMatcher, FileFilter
Defined in:
lib/rubocop/cop/style/rbs_inline/data_define_with_block.rb,
sig/rubocop/cop/style/rbs_inline/data_define_with_block.rbs

Overview

Checks for Data.define calls with a block.

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

NOTE: This is a known limitation of RBS::Inline. See https://github.com/soutaro/rbs-inline/pull/183 for the upstream fix.

Examples:

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

# good
User = Data.define(:name, :role)

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

Constant Summary collapse

MSG =

Returns:

  • (::String)
"Do not use `Data.define` with a block. RBS::Inline does not parse block contents, " \
"so methods defined in the block will not be recognized. Keep the `Data.define` call " \
"and move the methods into %<destination>s."

Constants included from FileFilter

FileFilter::MAGIC_COMMENT_DISABLED, FileFilter::MAGIC_COMMENT_ENABLED

Constants included from ModeConfig

ModeConfig::SUPPORTED_MODES

Instance Method Summary collapse

Methods included from ASTUtils

#args_node_for, #assigned_constant_name, #end_line, #method_parameter_list_end_line, #name_location, #source!, #value_to_sym

Methods included from DataClassMatcher

#struct_like_class?

Methods included from FileFilter

#add_offense, #on_new_investigation, #rbs_inline_disabled?, #rbs_inline_enabled?, #rbs_inline_file_skipped?, #skip_by_mode?

Methods included from ModeConfig

#configured_mode, #validate_config

Instance Method Details

#destination(node) ⇒ String

The constant the definition is assigned to is the class to reopen.

RBS:

  • node: RuboCop::AST::Node

Parameters:

  • node (RuboCop::AST::Node)

Returns:

  • (String)


53
54
55
56
57
58
# File 'lib/rubocop/cop/style/rbs_inline/data_define_with_block.rb', line 53

def destination(node) #: String
  class_name = assigned_constant_name(node)
  return "a `class` that reopens it" unless class_name

  "`class #{class_name} ... end` written after it"
end

#on_send(node) ⇒ void

This method returns an undefined value.

RBS:

  • node: RuboCop::AST::SendNode

Parameters:

  • node (RuboCop::AST::SendNode)


40
41
42
43
44
45
46
47
# File 'lib/rubocop/cop/style/rbs_inline/data_define_with_block.rb', line 40

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

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

  add_offense(node, message: format(MSG, destination: destination(block_node)))
end