Class: Serviz::Workflow

Inherits:
Base
  • Object
show all
Defined in:
lib/serviz/workflow.rb

Instance Attribute Summary

Attributes inherited from Base

#errors, #result

Class Method Summary collapse

Instance Method Summary collapse

Methods inherited from Base

call, #error_messages, #failure?, #success?

Constructor Details

#initialize(*args, **kwargs) ⇒ Workflow

Returns a new instance of Workflow.



15
16
17
18
19
# File 'lib/serviz/workflow.rb', line 15

def initialize(*args, **kwargs)
  @last_step = nil
  @args = args
  @kwargs = kwargs
end

Class Method Details

.step(service_class, params: nil, if: nil) ⇒ Object



3
4
5
6
7
8
9
# File 'lib/serviz/workflow.rb', line 3

def self.step(service_class, params: nil, if: nil)
  steps << {
    service_class: service_class,
    params: params,
    condition: binding.local_variable_get(:if)
  }
end

.stepsObject



11
12
13
# File 'lib/serviz/workflow.rb', line 11

def self.steps
  @steps ||= []
end

Instance Method Details

#callObject



21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
# File 'lib/serviz/workflow.rb', line 21

def call
  self.class.steps.each do |step_config|
    # Check if condition is provided and evaluate it
    if step_config[:condition] && !step_config[:condition].call(@last_step)
      next
    end

    # Determine parameters to use
    operation = if step_config[:params]
      # Use step-specific params
      step_params = if step_config[:params].is_a?(Proc)
                      step_config[:params].call(self)
                    else
                      step_config[:params]
                    end
      step_config[:service_class].call(**step_params)
    else
      # Use workflow args/kwargs
      step_config[:service_class].call(*@args, **@kwargs)
    end
    
    # Accumulate errors if the service failed
    if operation.failure?
      self.errors.concat(operation.errors)
    end

    # Update last result and overall result
    @last_step = operation
    self.result = operation.result
  end

  self
end