class CouchRest::Validation::FormatValidator

@author Guy van den Berg @since 0.9

Constants

FORMATS

Public Instance Methods

call(target) click to toggle source
# 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

Public Class Methods

new(field_name, options = {}, &b) click to toggle source
# 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