Class: Rubocop::Cop::CustomErrorClass

Inherits:
RuboCop::Cop::Base
  • Object
show all
Extended by:
RuboCop::Cop::AutoCorrector
Defined in:
lib/rubocop/cop/custom_error_class.rb

Overview

Makes sure that custom error classes, when empty, are declared with Class.new.

Examples:

# bad
class FooError < StandardError
end

# okish
class FooError < StandardError; end

# good
FooError = Class.new(StandardError)

Constant Summary collapse

MSG =
'Use `Class.new(SuperClass)` to define an empty custom error class.'

Instance Method Summary collapse

Instance Method Details

#on_class(node) ⇒ Object



23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
# File 'lib/rubocop/cop/custom_error_class.rb', line 23

def on_class(node)
  parent = node.parent_class
  body = node.body

  return if body

  parent_klass = class_name_from_node(parent)

  return unless parent_klass&.to_s&.end_with?('Error')

  add_offense(node) do |corrector|
    klass = node.identifier
    parent = node.parent_class

    replacement = "#{class_name_from_node(klass)} = Class.new(#{class_name_from_node(parent)})"

    corrector.replace(node.source_range, replacement)
  end
end