Class: CouchRest::Validation::LengthValidator

Inherits:
GenericValidator show all
Defined in:
lib/couchrest/validation/validators/length_validator.rb

Overview

Author:

  • Guy van den Berg

Since:

  • 0.9

Instance Attribute Summary

Attributes inherited from GenericValidator

#field_name, #if_clause, #unless_clause

Instance Method Summary collapse

Methods inherited from GenericValidator

#==, #add_error, #execute?

Constructor Details

#initialize(field_name, options) ⇒ LengthValidator

Returns a new instance of LengthValidator.

Since:

  • 0.9



33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
# File 'lib/couchrest/validation/validators/length_validator.rb', line 33

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



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
84
85
86
# File 'lib/couchrest/validation/validators/length_validator.rb', line 49

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 = CouchRest.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 = ValidationErrors.default_error_message(:length_between, field, min, max)
    end
  when :min then
    unless valid = field_value.size >= min
      error_message = ValidationErrors.default_error_message(:too_short, field, min)
    end
  when :max then
    unless valid = field_value.size <= max
      error_message = ValidationErrors.default_error_message(:too_long, field, max)
    end
  when :equals then
    unless valid = field_value.size == equal
      error_message = ValidationErrors.default_error_message(:wrong_length, field, equal)
    end
  end

  error_message = @options[:message] || error_message

  add_error(target, error_message, field_name) unless valid

  return valid
end