Class: DataMapper::Validate::FormatValidator

Inherits:
GenericValidator show all
Includes:
DataMapper::Validate::Format::Email, DataMapper::Validate::Format::Url
Defined in:
lib/gems/dm-validations-0.9.9/lib/dm-validations/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

#if_clause, #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?, #field_name

Constructor Details

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

Returns a new instance of FormatValidator.

Since:

  • 0.9



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

def initialize(field_name, options = {}, &b)
  super(field_name, options)
  @field_name, @options = field_name, options
  @options[:allow_nil] = false unless @options.has_key?(: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
49
50
51
# File 'lib/gems/dm-validations-0.9.9/lib/dm-validations/format_validator.rb', line 26

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

  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 =~ validator
    else
      raise UnknownValidationFormat, "Can't determine how to validate #{target.class}##{@field_name} with #{validator.inspect}"
  end

  return true if valid

  field = Extlib::Inflection.humanize(@field_name)
  error_message = @options[:message] || '%s has an invalid format'.t(field)
  error_message = error_message.call(field, value) if error_message.respond_to?(:call)

  add_error(target, error_message, @field_name)

  false
end