Class: RuboCop::Cop::Operandi::NoDirectInstantiation

Inherits:
Base
  • Object
show all
Defined in:
lib/operandi/rubocop/cop/operandi/no_direct_instantiation.rb

Overview

Prevents direct instantiation of service classes with .new. Services should be called using .run, .run!, or .call.

Examples:

# bad
UserService.new(name: "John")
User::Create.new(params: {})

# good
UserService.run(name: "John")
UserService.run!(name: "John")
UserService.call(name: "John")
User::Create.run(params: {})

ServicePattern: 'Service$' (default)

# Matches class names ending with "Service"
UserService.new  # offense
UserCreator.new  # no offense (doesn't match pattern)

ServicePattern: '(Service|Creator)$'

# Matches class names ending with "Service" or "Creator"
UserService.new  # offense
UserCreator.new  # offense

Constant Summary collapse

MSG =
"Use `.run`, `.run!`, or `.call` instead of `.new` for service classes."
RESTRICT_ON_SEND =
[:new].freeze

Instance Method Summary collapse

Instance Method Details

#on_send(node) ⇒ Object



35
36
37
38
39
40
# File 'lib/operandi/rubocop/cop/operandi/no_direct_instantiation.rb', line 35

def on_send(node)
  return unless node.method_name == :new
  return unless service_class?(node.receiver)

  add_offense(node)
end