Class: DataValidator::Validator

Inherits:
Object
  • Object
show all
Defined in:
lib/data_validator.rb

Instance Attribute Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(params, rules) ⇒ Validator

Returns a new instance of Validator.



11
12
13
14
15
# File 'lib/data_validator.rb', line 11

def initialize(params, rules)
  @params = params
  @rules  = rules
  @errors = {}
end

Instance Attribute Details

#errorsObject

Returns the value of attribute errors.



9
10
11
# File 'lib/data_validator.rb', line 9

def errors
  @errors
end

Instance Method Details

#error?Boolean

Returns:

  • (Boolean)


41
42
43
# File 'lib/data_validator.rb', line 41

def error?
  errors.present?
end

#valid?Boolean

Returns:

  • (Boolean)


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/data_validator.rb', line 17

def valid?
  @rules.each_pair do |key, rule|
    is_allow_nil   = rule.delete :allow_nil
    is_allow_blank = rule.delete :allow_blank
    next if @params[key].nil? && is_allow_nil
    next if @params[key].blank? && is_allow_blank

    rule.each_pair do |validator, options|
      klass = "#{validator.capitalize}Validator"
      constant   = Object
      constant   = constant.const_get "DataValidator"
      validation = constant.const_get(klass).new(key, @params[key], options, errors)
      validation.check_validity!
      validation.validate
    end
  end

  if error?
    return false
  else
    return true
  end
end