Class: DataMapper::Validations::LengthValidator

Inherits:
GenericValidator show all
Defined in:
lib/dm-validations/validators/length_validator.rb

Instance Attribute Summary

Attributes inherited from GenericValidator

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

Instance Method Summary collapse

Methods inherited from GenericValidator

#==, #add_error, #evaluate_conditional_clause, #execute?, #inspect, #optional?, #set_optional_by_default

Constructor Details

#initialize(field_name, options) ⇒ LengthValidator

Initialize a length validator

Parameters:

  • field_name (Symbol)

    the name of the field to validate

  • options (Hash)

    the validator options



14
15
16
17
18
19
20
21
22
23
24
25
# File 'lib/dm-validations/validators/length_validator.rb', line 14

def initialize(field_name, options)
  super

  @equal = options[:is]      || options[:equals]
  @range = options[:within]  || options[:in]
  @min   = options[:minimum] || options[:min]
  @max   = options[:maximum] || options[:max]

  if @min && @max
    @range ||= @min..@max
  end
end

Instance Method Details

#call(target) ⇒ Boolean

Test the resource field for validity

Examples:

when the resource field is valid

validator.call(valid_resource)  # => true

when the resource field is not valid

validator.call(invalid_resource)  # => false

Parameters:

  • target (Resource)

    the Resource to test

Returns:

  • (Boolean)

    true if the field is valid, false if not



43
44
45
46
47
48
49
50
51
# File 'lib/dm-validations/validators/length_validator.rb', line 43

def call(target)
  value = target.validation_property_value(field_name)
  return true if optional?(value)

  return true unless error_message = error_message_for(value)

  add_error(target, error_message, field_name)
  false
end