Module: Validations

Included in:
Model
Defined in:
lib/volt/models/validations.rb

Overview

Include in any class to get validation logic

Defined Under Namespace

Modules: ClassMethods

Class Method Summary collapse

Instance Method Summary collapse

Class Method Details

.included(base) ⇒ Object



18
19
20
# File 'lib/volt/models/validations.rb', line 18

def self.included(base)
  base.send :extend, ClassMethods
end

Instance Method Details

#errors(marked_only = false) ⇒ Object



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
80
81
82
83
# File 'lib/volt/models/validations.rb', line 48

def errors(marked_only=false)
  errors = {}

  validations = self.class.validations

  if validations
    # Merge into errors, combining any error arrays
    merge = Proc.new do |new_errors|
      errors.merge!(new_errors) do |key, new_val, old_val|
        new_val + old_val
      end
    end

    # Run through each validation
    validations.each_pair do |field_name, options|
      if marked_only
        # When marked only, skip any validations on non-marked fields
        next unless @marked_fields && @marked_fields[field_name]
      end

      options.each_pair do |validation, args|
        # Call the specific validator, then merge the results back
        # into one large errors hash.
        klass = validation_class(validation, args)

        if klass
          validate_with(merge, klass, field_name, args)
        else
          raise "validtion type #{validation} is not specified."
        end
      end
    end
  end

  return errors
end

#exclude_from_errors!(field_name) ⇒ Object

Sometimes we want to skip checking a field until some event has happened (usually a field has been typed in or blurred)



24
25
26
27
28
29
30
31
# File 'lib/volt/models/validations.rb', line 24

def exclude_from_errors!(field_name)
  @exclude_from_errors ||= {}
  @exclude_from_errors[field_name] = true

  @include_in_errors.delete(field_name) if @include_in_errors

  trigger_for_methods!('changed', :errors, :marked_errors)
end

#mark_field!(field_name, trigger_changed = true) ⇒ Object

Once a field is ready, we can use include_in_errors! to start showing its errors.



35
36
37
38
39
40
41
42
# File 'lib/volt/models/validations.rb', line 35

def mark_field!(field_name, trigger_changed=true)
  @marked_fields ||= {}
  @marked_fields[field_name] = true

  if trigger_changed
    trigger_for_methods!('changed', :errors, :marked_errors)
  end
end

#marked_errorsObject



44
45
46
# File 'lib/volt/models/validations.rb', line 44

def marked_errors
  errors(true)
end