Class: ValidationProfiler::Manager

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

Instance Method Summary collapse

Instance Method Details

#add_rule(key, rule) ⇒ Object

Called to add a custom validation rule to the manager

Parameters:

  • key (Symbol)

    The name of the rule

  • rule (ClassName)

    Class name of the validation rule to register.



41
42
43
44
45
46
47
# File 'lib/validation_profiler/manager.rb', line 41

def add_rule(key, rule)
  if ValidationProfiler::Rules::Manager.instance.nil?
    ValidationProfiler::Rules::Manager.new
  end

  ValidationProfiler::Rules::Manager.instance.add_rule(key, rule)
end

#validate(obj, profile, parent = nil) ⇒ ValidationManagerResult

Called to validate an object against a validation profile.

Parameters:

  • obj (Object)

    The object to validate

  • profile (ClassName)

    The class name of the validation profile to validate against

Returns:

  • (ValidationManagerResult)

    The result of the validation



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
# File 'lib/validation_profiler/manager.rb', line 9

def validate(obj, profile, parent = nil)
  result = ValidationProfiler::ManagerResult.new

  validation_rules = profile.class_variable_get(:@@validation_rules)

  validation_rules.each do |r|

    if ValidationProfiler::Rules::Manager.instance.nil?
      ValidationProfiler::Rules::Manager.new
    end

    rule = ValidationProfiler::Rules::Manager.instance.get_rule(r[:name])
    outcome = rule.validate(obj, r[:field], r[:attributes], parent)

    if outcome.is_a?(Array)
      result.errors += outcome.map(&:errors).flatten
    elsif outcome.is_a?(ValidationProfiler::ManagerResult) && !outcome.outcome
      result.errors += outcome.errors
    elsif !outcome
      result.errors.push(field: r[:field], message: rule.error_message(r[:field], r[:attributes], parent))
    end
  end

  result.outcome = result.errors.empty?

  result
end