Class: PoroValidator::Validator::Validations

Inherits:
BaseClass
  • Object
show all
Defined in:
lib/poro_validator/validator/validations.rb

Overview

Since:

  • 0.0.1

Class Method Summary collapse

Instance Method Summary collapse

Methods inherited from BaseClass

#<<, #run_validations, #validations, #validators

Constructor Details

#initialize(&block) ⇒ Validations

Returns a new instance of Validations.

Since:

  • 0.0.1



15
16
17
18
# File 'lib/poro_validator/validator/validations.rb', line 15

def initialize(&block)
  super()
  instance_eval(&block) if block_given?
end

Class Method Details

.build_validations(validations = []) ⇒ Object

Since:

  • 0.0.1



5
6
7
8
9
10
11
12
13
# File 'lib/poro_validator/validator/validations.rb', line 5

def self.build_validations(validations = [])
  inst = new
  unless validations.empty?
    validations.each do |validation|
      inst << validation
    end
  end
  inst
end

Instance Method Details

#build(attr, **options) ⇒ Object

Since:

  • 0.0.1



20
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
# File 'lib/poro_validator/validator/validations.rb', line 20

def build(attr, **options)
  @validators = options.reject do |k,v|
    [:if, :unless].include?(k)
  end

  @conditions = [] << options.select do |k,v|
    [:if, :unless].include?(k)
  end

  @validators.each do |validator,options|
    nested_conditions = {}
    if options.is_a?(::Hash)
      # Check if there are any nested conditions for a validator
      # options and select if it exists.
      #
      # e.g
      #   validates :foo, format: { with: "hello", unless: :foo_rule }
      nested_conditions = options.select do |k,v|
        [:if, :unless].include?(k)
      end

      # Remove the nested conditions from the validator options.
      unless nested_conditions.empty?
        options.reject! { |k,v| [:if, :unless].include?(k) }
        @conditions << nested_conditions
      end
    end

    self << { validator: Validation.build(attr, validator, options),
              conditions: @conditions.reject(&:empty?)
    }
  end
end