Module: Glue::Validation
- Defined in:
- lib/more/facets/validation.rb
Overview
Implements a meta-language for validating managed objects. Typically used in Validator objects but can be included in managed objects too.
Additional og-related validation macros can be found in lib/og/validation.
The following validation macros are available:
* validate_value
* validate_confirmation
* validate_format
* validate_length
* validate_inclusion
Og/Database specific validation methods are added in the file og/validation.rb
Example
class User
attr_accessor :name, String
attr_accessor :level, Fixnum
validate_length :name, :range => 2..6
validate_unique :name, :msg => :name_allready_exists
validate_format :name, :format => /[a-z]*/, :msg => 'invalid format', :on => :create
end
class CustomUserValidator
include Validation
validate_length :name, :range => 2..6, :msg_short => :name_too_short, :msg_long => :name_too_long
end
user = @request.fill(User.new)
user.level = 15
unless user.valid?
user.save
else
p user.errors[:name]
end
unless user.save
p user.errors.on(:name)
end
unless errors = CustomUserValidator.errors(user)
user.save
else
p errors[:name]
end
– TODO: all validation methods should imply validate_value. ++
Defined Under Namespace
Modules: ClassMethods Classes: Errors, Key
Instance Attribute Summary collapse
-
#errors ⇒ Object
If the validate method returns true, this attributes holds the errors found.
Instance Method Summary collapse
-
#valid? ⇒ Boolean
Call the #validate method for this object.
-
#validate(on = :save) ⇒ Object
Evaluate the class and see if it is valid.
Instance Attribute Details
#errors ⇒ Object
If the validate method returns true, this attributes holds the errors found.
150 151 152 |
# File 'lib/more/facets/validation.rb', line 150 def errors @errors end |
Instance Method Details
#valid? ⇒ Boolean
Call the #validate method for this object. If validation errors are found, sets the returns true.
157 158 159 160 |
# File 'lib/more/facets/validation.rb', line 157 def valid? validate @errors.empty? end |
#validate(on = :save) ⇒ Object
Evaluate the class and see if it is valid. Can accept any parameter for ‘on’ event, and defaults to :save
166 167 168 169 170 171 172 173 174 |
# File 'lib/more/facets/validation.rb', line 166 def validate(on = :save) @errors = Errors.new return if self.class.validations.length == 0 for event, block in self.class.validations block.call(self) if event == on.to_sym end end |