Class: CouchRest::Validation::FormatValidator

Inherits:
GenericValidator show all
Includes:
CouchRest::Validation::Format::Email, CouchRest::Validation::Format::Url
Defined in:
lib/couchrest/validation/validators/format_validator.rb

Overview

Author:

  • Guy van den Berg

Since:

  • 0.9

Constant Summary collapse

FORMATS =

Since:

  • 0.9

{}

Constants included from CouchRest::Validation::Format::Url

CouchRest::Validation::Format::Url::Url

Constants included from CouchRest::Validation::Format::Email

CouchRest::Validation::Format::Email::EmailAddress

Instance Attribute Summary

Attributes inherited from GenericValidator

#field_name, #if_clause, #unless_clause

Instance Method Summary collapse

Methods included from CouchRest::Validation::Format::Url

included

Methods included from CouchRest::Validation::Format::Email

included

Methods inherited from GenericValidator

#==, #add_error, #execute?

Constructor Details

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

Returns a new instance of FormatValidator.

Since:

  • 0.9



41
42
43
44
45
# File 'lib/couchrest/validation/validators/format_validator.rb', line 41

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



47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
# File 'lib/couchrest/validation/validators/format_validator.rb', line 47

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

  error_message = @options[:message] || ValidationErrors.default_error_message(:invalid, field_name)

  field = field_name.to_s.humanize
  error_message = error_message.call(field, value) if error_message.respond_to?(:call)

  add_error(target, error_message, field_name)

  false
end