Class: DataMapper::Validations::FormatValidator
- Inherits:
-
GenericValidator
- Object
- GenericValidator
- DataMapper::Validations::FormatValidator
- Includes:
- Helpers::Email
- Defined in:
- lib/data_mapper/validations/format_validator.rb
Defined Under Namespace
Classes: UnknownValidationFormat
Constant Summary collapse
- ERROR_MESSAGES =
{ :invalid => '#{field} is invalid', :invalid_email => '#{value} is not a valid email address' }
- FORMATS =
{ :email_address => [lambda { |email_address| email_address =~ DataMapper::Validations::Helpers::Email::RFC2822::EmailAddress }, :invalid_email] }
Instance Method Summary collapse
- #call(target) ⇒ Object
-
#initialize(field_name, options = {}, &b) ⇒ FormatValidator
constructor
A new instance of FormatValidator.
Methods inherited from GenericValidator
#add_error, #validation_error_message
Constructor Details
#initialize(field_name, options = {}, &b) ⇒ FormatValidator
Returns a new instance of FormatValidator.
21 22 23 |
# File 'lib/data_mapper/validations/format_validator.rb', line 21 def initialize(field_name, = {}, &b) @field_name, @options = field_name, end |
Instance Method Details
#call(target) ⇒ Object
25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 |
# File 'lib/data_mapper/validations/format_validator.rb', line 25 def call(target) field_value = target.instance_variable_get("@#{@field_name}") return true if @options[:allow_nil] && field_value.nil? validation = (@options[:as] || @options[:with]) = :invalid # Figure out what to use as the actual validator. If a symbol is passed to :as, look up # the canned validation in FORMATS. validator = if validation.is_a? Symbol if FORMATS[validation].is_a? Array = FORMATS[validation][1] || :invalid FORMATS[validation][0] else FORMATS[validation] || validation end else validation end valid = case validator when Proc then validator.call(field_value) when Regexp then validator =~ field_value else raise UnknownValidationFormat, "Can't determine how to validate #{target.class}##{@field_name} with #{validator.inspect}" end unless valid field = Inflector.humanize(@field_name) value = target.instance_variable_get("@#{@field_name}") = (ERROR_MESSAGES[], nil, binding) add_error(target, , @field_name) end return valid end |