Class: Validation::Validator

Inherits:
Object
  • Object
show all
Includes:
Rules
Defined in:
lib/validation/validator.rb

Instance Attribute Summary collapse

Instance Method Summary collapse

Methods included from Rules

#validates_match, #validates_required

Constructor Details

#initializeValidator

Returns a new instance of Validator.



10
11
12
13
# File 'lib/validation/validator.rb', line 10

def initialize
  @rules = {}
  @errors = {}
end

Instance Attribute Details

#errorsObject (readonly)

Returns the value of attribute errors.



8
9
10
# File 'lib/validation/validator.rb', line 8

def errors
  @errors
end

#rulesObject (readonly)

Returns the value of attribute rules.



7
8
9
# File 'lib/validation/validator.rb', line 7

def rules
  @rules
end

Instance Method Details

#add_rule(field, rule, message) ⇒ Object



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

def add_rule(field, rule, message)
  @rules[field] ||= []
  @rules[field].push({'rule' => rule, 'message' => message})
end

#reset_errorsObject



39
40
41
# File 'lib/validation/validator.rb', line 39

def reset_errors
  @errors = {}
end

#valid?Boolean

Returns:

  • (Boolean)


35
36
37
# File 'lib/validation/validator.rb', line 35

def valid?
  @errors.empty?
end

#validate(params) ⇒ Object



20
21
22
23
24
25
26
27
28
29
30
31
32
33
# File 'lib/validation/validator.rb', line 20

def validate(params)
  reset_errors
  @rules.each do |field, rules|
    rules.each do |rule|
      method, *args = rule['rule'].split(',').map(&:strip)
      args = [params, field] + args
      unless send("validates_#{method}", *args)
        @errors[field] ||= []
        @errors[field].push(rule['message'])
      end
    end
  end
  valid?
end