Class: PoroValidator::Validators::WithValidator

Inherits:
BaseClass
  • Object
show all
Defined in:
lib/poro_validator/validators/with_validator.rb

Overview

Since:

  • 0.0.1

Instance Attribute Summary

Attributes inherited from BaseClass

#attribute

Instance Method Summary collapse

Methods inherited from BaseClass

#__validate__, #context, #errors, #initialize, #nested?, #options, #value

Constructor Details

This class inherits a constructor from PoroValidator::Validators::BaseClass

Instance Method Details

#validate(attribute, value, options) ⇒ Object

Since:

  • 0.0.1



4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
# File 'lib/poro_validator/validators/with_validator.rb', line 4

def validate(attribute, value, options)
  validator_class = options.fetch(:with)
  case validator_class
  when Class
    klass = validator_class.new

    if context.entity.is_a?(::Hash)
      entity = context.entity[attribute]

      if entity.nil? || entity.is_a?(::Symbol) || entity.is_a?(::String)
        klass.valid?(attribute => entity)
      else
        klass.valid?(context.entity[attribute] || {})
      end
    else
      entity = context.entity.public_send(attribute)
      if entity.nil? || entity.is_a?(::Symbol) || entity.is_a?(::String)
        klass.valid?(attribute => entity)
      else
        klass.valid?(entity)
      end
    end

    klass.errors.public_send(:store).data.each do |k,v|
      if k.to_s == attribute.to_s
        errors.add(attribute, v.pop)
      else
        errors.add([attribute, k.to_sym], v.pop)
      end
    end
  else
    raise ::PoroValidator::InvalidValidator.new(
      "Requires a class object for this validator."
    )
  end
end