Class: SimpleValidate::ValidatesLengthOf

Inherits:
ValidatesBase show all
Defined in:
lib/simple_validate/validates_length_of.rb

Constant Summary collapse

VALIDATORS =
i[maximum minimum in is].freeze

Instance Attribute Summary

Attributes inherited from ValidatesBase

#attribute, #condition

Instance Method Summary collapse

Constructor Details

#initialize(attribute, options) ⇒ ValidatesLengthOf

Returns a new instance of ValidatesLengthOf.

Raises:

  • (ArgumentError)


7
8
9
10
11
12
13
14
15
16
# File 'lib/simple_validate/validates_length_of.rb', line 7

def initialize(attribute, options)
  @validator = options.keys.first

  raise ArgumentError, "Invalid length option" unless VALIDATORS.include?(@validator)

  @valid_length = options[@validator]
  @allow_nil = options[:allow_nil]

  super(attribute, options[:message], options[:if] || proc { true })
end

Instance Method Details

#messageObject



18
19
20
21
22
23
24
25
26
27
# File 'lib/simple_validate/validates_length_of.rb', line 18

def message
  @message = case @validator
             when :minimum
               "is too short"
             when :maximum
               "is too long"
             else
               "is not valid length"
             end
end

#valid?(instance) ⇒ Boolean

Returns:

  • (Boolean)


42
43
44
45
46
47
48
49
# File 'lib/simple_validate/validates_length_of.rb', line 42

def valid?(instance)
  val = instance.send(attribute)

  return true if val.nil? && @allow_nil == true

  actual_length = val&.length
  valid_length?(actual_length)
end

#valid_length?(actual_length) ⇒ Boolean

Returns:

  • (Boolean)


29
30
31
32
33
34
35
36
37
38
39
40
# File 'lib/simple_validate/validates_length_of.rb', line 29

def valid_length?(actual_length)
  case @validator
  when :minimum
    actual_length >= @valid_length
  when :maximum
    actual_length <= @valid_length
  when :in
    @valid_length.member?(actual_length)
  when :is
    actual_length == @valid_length
  end
end