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

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

Overview

Qyu::Workers::Concerns::PayloadValidator

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 :hotels,     presence: true, type: :array
validates :account_id, absence: true,  if: :customer_id
validates :account_id, presence: true, unless: :customer_id

end

Instance Method Summary collapse

Instance Method Details

#validate_payload!(model) ⇒ nil

Validates payload in processing task and raises a Qyu::Errors::PayloadValidationError if any of the conditions do not hold up


43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
# File 'lib/qyu/workers/concerns/payload_validator.rb', line 43

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 = {}) ⇒ Hash

Adds a validation option to worker

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

32
33
34
35
# File 'lib/qyu/workers/concerns/payload_validator.rb', line 32

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