Class: Fractor::Workflow::Helpers::ValidationWorker

Inherits:
Fractor::Worker show all
Defined in:
lib/fractor/workflow/helpers.rb

Overview

Worker for validation Implement the validate method

Example:

class ValidateAge < Fractor::Workflow::Helpers::ValidationWorker
def validate(input)
  return unless input.age < 0
  add_error("Age must be positive")
end
end

Instance Method Summary collapse

Methods inherited from Fractor::Worker

effective_timeout, input_type, output_type, timeout, #timeout

Constructor Details

#initializeValidationWorker

Returns a new instance of ValidationWorker.



153
154
155
156
# File 'lib/fractor/workflow/helpers.rb', line 153

def initialize
  super
  @errors = []
end

Instance Method Details

#add_error(message) ⇒ Object

Add a validation error



175
176
177
# File 'lib/fractor/workflow/helpers.rb', line 175

def add_error(message)
  @errors << message
end

#build_output(input, errors) ⇒ Object

Override to customize output format Default: returns hash with valid? flag and errors



181
182
183
184
185
186
187
# File 'lib/fractor/workflow/helpers.rb', line 181

def build_output(input, errors)
  {
    valid: errors.empty?,
    errors: errors,
    input: input,
  }
end

#process(work) ⇒ Object



158
159
160
161
162
163
164
165
166
# File 'lib/fractor/workflow/helpers.rb', line 158

def process(work)
  input = work.input
  @errors = []

  validate(input)

  output = build_output(input, @errors)
  Fractor::WorkResult.new(result: output, work: work)
end

#validate(input) ⇒ Object

Override in subclasses to define validation logic Use add_error(message) to record errors

Raises:

  • (NotImplementedError)


170
171
172
# File 'lib/fractor/workflow/helpers.rb', line 170

def validate(input)
  raise NotImplementedError, "Subclasses must implement #validate"
end