Class: DataMapper::Validate::LengthValidator

Constructor Summary

public initialize(field_name, options)
[View source]


10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
# File 'dm-more/dm-validations/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

Public Visibility

Public Instance Method Summary

#call(target)

Public Instance Methods Inherited from DataMapper::Validate::GenericValidator

add_error, execute?, field_name

Public Instance Methods Inherited from Object

validatable?

Public Instance Method Details

call

public call(target)
[View source]


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
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
# File 'dm-more/dm-validations/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]

  add_error(target, error_message, @field_name) unless valid

  return valid
end