Class: Rulix::Validators::LengthValidator

Inherits:
Object
  • Object
show all
Defined in:
lib/rulix/validators/length_validator.rb

Instance Attribute Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(options = nil) ⇒ LengthValidator

Returns a new instance of LengthValidator.



6
7
8
9
10
11
12
13
14
# File 'lib/rulix/validators/length_validator.rb', line 6

def initialize options = nil
  options ||= {}
  min = options[:min] || 0
  max = options[:max]

  self.exactly = options[:exactly]
  self.min = min
  self.max = max
end

Instance Attribute Details

#exactlyObject

Returns the value of attribute exactly.



4
5
6
# File 'lib/rulix/validators/length_validator.rb', line 4

def exactly
  @exactly
end

#maxObject

Returns the value of attribute max.



4
5
6
# File 'lib/rulix/validators/length_validator.rb', line 4

def max
  @max
end

#minObject

Returns the value of attribute min.



4
5
6
# File 'lib/rulix/validators/length_validator.rb', line 4

def min
  @min
end

Instance Method Details

#call(string) ⇒ Object



16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
# File 'lib/rulix/validators/length_validator.rb', line 16

def call string
  return [false, "can't be nil"] unless string

  if exactly.nil?
    if min && max
      (min..max).cover?(string.length) || [false, error_message(string)]
    elsif min && !max
      string.length >= min || [false, error_message(string)]
    elsif max && !min
      string.length <= max || [false, error_message(string)]
    end
  else
    exactly == string.length || [false, exact_error_message]
  end
end

#error_message(string) ⇒ Object



36
37
38
39
40
41
42
# File 'lib/rulix/validators/length_validator.rb', line 36

def error_message string
  if string.length < min
    "must be at least #{min} characters long"
  elsif string.length > max
    "cannot be longer than #{max} characters"
  end
end

#exact_error_messageObject



32
33
34
# File 'lib/rulix/validators/length_validator.rb', line 32

def exact_error_message
  "must be exactly #{exactly} characters long"
end

#to_procObject



44
45
46
# File 'lib/rulix/validators/length_validator.rb', line 44

def to_proc
  method(:call)
end