Add validation support to models.

Methods
Attributes
[RW] validation_errors The validation errors.
Public Instance methods
valid?()

Alias for #validates?

validate_format(*args)

Validate the format of the given String attributes.

Arguments:

  • a collection of attribute symbols
  • an optional hash with configuration:
    • format = a regular expression describing the valid format
    • msg = the error message
    • on = if set to :insert only validates on insert

Example:

  class User
    attr_accessor :name, String
    validate_value :name, :msg => "Name required"
  end
    # File lib/og/validation.rb, line 69
69:     def validate_format(*args)
70:       options = args.last.is_a?(Hash) ? args.pop : {}
71:       raise "No format given" unless format = options[:format]
72:       msg = options.fetch(:msg, "No value")
73:       on_insert = options.fetch(:on, false) == :insert
74:             
75:       for a in args
76:         validation_rules! << lambda do
77:           next if self.saved? if on_insert
78:           if val = instance_variable_get("@#{a}") and a !~ format
79:             @validation_errors[a] = msg
80:           end 
81:         end 
82:       end
83:     end
validate_value(*args)

Validate that the given attributes have values.

Arguments:

  • a collection of attribute symbols
  • an optional hash with configuration:
    • msg = the error message
    • on = if set to :insert only validates on insert

Example:

  class User
    attr_accessor :name, String
    validate_value :name, :msg => "Name required"
    validate_value :name, :on => :insert
  end
    # File lib/og/validation.rb, line 37
37:     def validate_value(*args)
38:       options = args.last.is_a?(Hash) ? args.pop : {}
39:       msg = options.fetch(:msg, "No value")
40:       on_insert = options.fetch(:on, false) == :insert
41:                   
42:       for a in args
43:         validation_rules! << lambda do
44:           next if self.saved? if on_insert
45:           if instance_variable_get("@#{a}").blank?
46:             @validation_errors[a] = msg
47:           end 
48:         end 
49:       end
50:     end
validates?()

Does the model validate? Some (costly) validations are only checked on insert.

This method is also aliased as valid?
    # File lib/og/validation.rb, line 90
90:   def validates?
91:     @validation_errors = {}
92:     
93:     for rule in self.class.validation_rules
94:       instance_eval(&rule)
95:     end
96:     
97:     return @validation_errors.empty?
98:   end