lib/volt/models/validators/format_validator.rb in volt-0.8.27.beta3 vs lib/volt/models/validators/format_validator.rb in volt-0.8.27.beta4
- old
+ new
@@ -1,45 +1,44 @@
module Volt
+ # Validates the format of a field against any number of block or regex
+ # criteria
class FormatValidator
# Creates a new instance with the provided options and returns it's errors
#
- # @note the second param +old_model+ is unused and will soon be removed,
- # you can pass nil in the mean time
- #
# @example
# options = { with: /.+@.+/, message: 'must include an @ symobl' }
#
- # FormatValidator.validate(user, nil, 'email', options)
+ # FormatValidator.validate(user, 'email', options)
#
# @example
# numbers_only = /^\d+$/
# sum_equals_ten = ->(s) { s.chars.map(&:to_i).reduce(:+) == 10 }
#
# options = [
# { with: numbers_only, message: 'must include only numbers' },
# { with: sum_equals_ten, message: 'must add up to 10' }
# ]
#
- # FormatValidator.validate(user, nil, 'email', options)
+ # FormatValidator.validate(user, 'email', options)
#
# @param model [Volt::Model] the model being validated
- # @param old_model [NilClass] no longer used, will be removed
# @param field_name [String] the name of the field being validated
#
# @param options (see #apply)
# @option options (see #apply)
#
# @return (see #errors)
- def self.validate(model, old_model, field_name, options)
+ def self.validate(model, field_name, options)
new(model, field_name).apply(options).errors
end
# @param model [Volt::Model] the model being validated
# @param field_name [String] the name of the field being validated
def initialize(model, field_name)
@name = field_name
- @value = model.read_attribute field_name
+ @value = model.get field_name
+
@criteria = []
end
# Applies criteria to the validator in a variety of forms
#
@@ -55,10 +54,22 @@
# - +"is invalid because..."+
#
# @return [self] returns itself for chaining
def apply(options)
return apply_list options if options.is_a? Array
+
+ options = case options
+ when true
+ default_options
+ when Hash
+ if default_options.is_a? Hash
+ default_options.merge options
+ else
+ options
+ end
+ end
+
with options[:with], options[:message]
self
end
# Returns the first of the validation errors or an empty hash
@@ -103,9 +114,13 @@
private
def apply_list(array)
array.each { |options| apply options }
self
+ end
+
+ def default_options
+ {}
end
def test(criterion)
return false unless @value.respond_to? :match