Class: DataMapper::Validate::FormatValidator

Inherits:
GenericValidator show all
Includes:
DataMapper::Validate::Format::Email, DataMapper::Validate::Format::Url
Defined in:
lib/dm-validations/validators/format_validator.rb

Overview

Author:

  • Guy van den Berg

Since:

  • 0.9

Constant Summary collapse

FORMATS =

Since:

  • 0.9

{}

Constants included from DataMapper::Validate::Format::Url

DataMapper::Validate::Format::Url::Url

Constants included from DataMapper::Validate::Format::Email

DataMapper::Validate::Format::Email::EmailAddress

Instance Attribute Summary

Attributes inherited from GenericValidator

#field_name, #humanized_field_name, #if_clause, #options, #unless_clause

Instance Method Summary collapse

Methods included from DataMapper::Validate::Format::Url

included

Methods included from DataMapper::Validate::Format::Email

included

Methods inherited from GenericValidator

#==, #add_error, #execute?, #inspect

Constructor Details

#initialize(field_name, options = {}) ⇒ FormatValidator

Returns a new instance of FormatValidator.

Since:

  • 0.9



20
21
22
23
24
# File 'lib/dm-validations/validators/format_validator.rb', line 20

def initialize(field_name, options = {})
  super

  @options[:allow_nil] = true unless @options.include?(:allow_nil)
end

Instance Method Details

#call(target) ⇒ Object

Since:

  • 0.9



26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
# File 'lib/dm-validations/validators/format_validator.rb', line 26

def call(target)
  value = target.validation_property_value(field_name)
  return true if @options[:allow_nil] && value.blank?

  validation = @options[:as] || @options[:with]

  raise "No such predefined format '#{validation}'" if validation.is_a?(Symbol) && !FORMATS.has_key?(validation)
  validator = validation.is_a?(Symbol) ? FORMATS[validation][0] : validation

  valid = case validator
    when Proc   then validator.call(value)
    when Regexp then (value.is_a?(Fixnum) ? value.to_s : value) =~ validator
    else
      raise UnknownValidationFormat, "Can't determine how to validate #{target.class}##{field_name} with #{validator.inspect}"
  end

  return true if valid

  error_message = @options[:message] || ValidationErrors.default_error_message(:invalid, field_name)
  add_error(target, error_message.try_call(humanized_field_name, value), field_name)

  false
end