Class: DataMapper::Validate::LengthValidator

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

Overview

Author:

  • Guy van den Berg

Since:

  • 0.9

Instance Attribute Summary

Attributes inherited from GenericValidator

#if_clause, #unless_clause

Instance Method Summary collapse

Methods inherited from GenericValidator

#==, #add_error, #execute?, #field_name

Constructor Details

#initialize(field_name, options) ⇒ LengthValidator

Returns a new instance of LengthValidator.

Since:

  • 0.9


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

def initialize(field_name, options)
  super
  @field_name = field_name
  @options = options

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

  @validation_method ||= :range if @range
  @validation_method ||= :min if @min && @max.nil?
  @validation_method ||= :max if @max && @min.nil?
  @validation_method ||= :equals unless @equal.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
52
53
54
55
56
57
58
59
60
61
62
63
# File 'lib/dm-validations/length_validator.rb', line 26

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

  field_value = '' if field_value.nil?

  # XXX: HACK seems hacky to do this on every validation, probably should
  #      do this elsewhere?
  field = Extlib::Inflection.humanize(@field_name)
  min = @range ? @range.min : @min
  max = @range ? @range.max : @max
  equal = @equal

  case @validation_method
  when :range then
    unless valid = @range.include?(field_value.size)
      error_message = '%s must be between %s and %s characters long'.t(field, min, max)
    end
  when :min then
    unless valid = field_value.size >= min
      error_message = '%s must be more than %s characters long'.t(field, min)
    end
  when :max then
    unless valid = field_value.size <= max
      error_message = '%s must be less than %s characters long'.t(field, max)
    end
  when :equals then
    unless valid = field_value.size == equal
      error_message = '%s must be %s characters long'.t(field, equal)
    end
  end

  error_message = @options[:message] || error_message

  add_error(target, error_message, @field_name) unless valid

  return valid
end