Class: Operandi::BaseWithContext

Inherits:
Object
  • Object
show all
Defined in:
lib/operandi/base_with_context.rb

Overview

Wrapper for running a service with a parent context or custom configuration. Created via Operandi::Base.with method.

Examples:

Running with parent service context

ChildService.with(self).run(data: value)

Running with custom configuration

MyService.with(use_transactions: false).run(name: "test")

Instance Method Summary collapse

Constructor Details

#initialize(service_class, parent_service, config) ⇒ BaseWithContext

Initialize a new context wrapper.

Parameters:

  • service_class (Class)

    the service class to run

  • parent_service (Base, nil)

    parent service for error/warning propagation

  • config (Hash)

    configuration overrides

Raises:

  • (ArgTypeError)

    if parent_service is not a Base subclass



19
20
21
22
23
24
25
26
27
28
# File 'lib/operandi/base_with_context.rb', line 19

def initialize(service_class, parent_service, config)
  @service_class = service_class
  @config = config
  @parent_service = parent_service

  return if parent_service.nil? || parent_service.is_a?(Operandi::Base)

  message = "#{parent_service.class} - must be a subclass of Operandi::Base"
  raise Operandi::ArgTypeError.new(message, service_class: @service_class)
end

Instance Method Details

#run(**kwargs) ⇒ Base

Run the service with the configured context.

Parameters:

  • kwargs (Hash)

    keyword arguments matching service arguments

Returns:

  • (Base)

    the executed service instance



34
35
36
# File 'lib/operandi/base_with_context.rb', line 34

def run(**kwargs)
  @service_class.new(extend_arguments(kwargs), @config, @parent_service).tap(&:call)
end

#run!(**kwargs) ⇒ Base

Run the service and raise an error if it fails.

Parameters:

  • kwargs (Hash)

    keyword arguments matching service arguments

Returns:

  • (Base)

    the executed service instance

Raises:



43
44
45
46
# File 'lib/operandi/base_with_context.rb', line 43

def run!(**kwargs)
  @config[:raise_on_error] = true
  run(**kwargs)
end