Class: LIVR::Validator

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

Class Method Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(rules, is_auto_trim = false) ⇒ Validator


3
4
5
6
7
8
9
10
11
# File 'lib/livr/validator.rb', line 3

def initialize(rules, is_auto_trim=false)
  @rules = rules
  @is_prepared = false
  @validator_builders = {}
  @validators = {}
  @is_auto_trim = is_auto_trim

  register_default_rules
end

Class Method Details

.register_default_rules(rules) ⇒ Object


13
14
15
16
# File 'lib/livr/validator.rb', line 13

def self.register_default_rules(rules)
  @@default_rules ||= {}
  @@default_rules.merge!(rules.with_indifferent_access)
end

Instance Method Details

#get_errorsObject


86
87
88
# File 'lib/livr/validator.rb', line 86

def get_errors
  @errors
end

#prepareObject


25
26
27
28
29
30
31
32
33
34
35
# File 'lib/livr/validator.rb', line 25

def prepare
  @rules.each do |field, field_rules|
    field_rules = Array.wrap(field_rules)
    @validators[field] = field_rules.map do |field_rule|
      rule_name, rule_args = parse_rule(field_rule)
      build_validator(rule_name, rule_args)
    end
    @is_prepared = true
  end
  self
end

#register_aliased_rule(_alias) ⇒ Object


18
19
20
21
22
23
# File 'lib/livr/validator.rb', line 18

def register_aliased_rule(_alias)
  # binding.pry
  # @validator_builders
  register_rules( _alias["name"] =>  AliasedRule.new(_alias) )
   # @@default_rules[_alias["name"]] = AliasedRule.new(_alias)
end

#register_rules(rules) ⇒ Object


81
82
83
84
# File 'lib/livr/validator.rb', line 81

def register_rules(rules)
  @validator_builders.merge!(rules)
  self
end

#validate(user_data) ⇒ Object


37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
# File 'lib/livr/validator.rb', line 37

def validate(user_data)
  prepare unless @is_prepared

  unless user_data.is_a?(Hash)
    @errors = 'FORMAT_ERROR'
    return
  end

  if @is_auto_trim
    user_data = auto_trim(user_data)
  end

  @result = {}
  @errors = {}

  @validators.each do |field, validators|
    next if validators.blank?
    next if !@rules.has_key?(field)

    value = user_data[field]
    validators.each do |validator|
      field_results = []
      field_value = @result.fetch(field, value)
      error_code = validator.call(field_value, user_data, field_results)

      if error_code
        @errors[field] = error_code
        break
      elsif field_results.present?
        @result[field] = field_results.first
      elsif user_data.has_key?(field) && !@result.has_key?(field)
        @result[field] = value
      end
    end
  end

  if @errors.present?
    return false
  else
    @errors = nil
    return @result
  end
end