Module: Qyu::Workers::Concerns::PayloadValidator

Included in:
Base
Defined in:
lib/qyu/workers/concerns/payload_validator.rb

Overview

Qyu::Concerns::PayloadValidator

Instance Method Summary collapse

Instance Method Details

#validate_payload!(model) ⇒ Object



26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
# File 'lib/qyu/workers/concerns/payload_validator.rb', line 26

def validate_payload!(model)
  return unless @_validations
  payload = Qyu::Utils.stringify_hash_keys(model.payload || {})
  validation_errors = {}
  @_validations.each do |attribute, opts|
    # example: attribute :name
    # example opts { presence: true, type: integer }
    next unless if_validation(payload, opts['if'])
    next unless unless_validation(payload, opts['unless'])
    opts.map do |option, value|
      error = run_validation(option, payload[attribute.to_s], value)
      # next if error is nil
      next unless error
      validation_errors["#{attribute}.#{option}"] = error
    end
  end

  if validation_errors.size.positive?
    fail Qyu::Errors::PayloadValidationError, validation_errors
  end
  nil
end

#validates(parameter, opts = {}) ⇒ Object

Adds ability to workers to perform validations on params for the task to be processed

Usage:

Qyu::Worker.new do

validates :user_id,    presence: true, type: :integer, unless: :no_user
validates :name,       presence: true, type: :string
validates :account_id, absence: true,  if: :customer_id
validates :account_id, presence: true, unless: :customer_id

end



21
22
23
24
# File 'lib/qyu/workers/concerns/payload_validator.rb', line 21

def validates(parameter, opts = {})
  @_validations ||= {}
  @_validations[parameter.to_s] = Qyu::Utils.stringify_hash_keys(opts)
end