Class: SimpleValidate::ValidatesLengthOf

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

Defined Under Namespace

Classes: InvalidLengthOption

Constant Summary collapse

VALID_LENGTH_OPTIONS =
%i[maximum minimum in is].freeze

Instance Attribute Summary collapse

Attributes inherited from ValidatesBase

#condition

Instance Method Summary collapse

Constructor Details

#initialize(attribute, options) ⇒ ValidatesLengthOf

Returns a new instance of ValidatesLengthOf.



11
12
13
14
15
# File 'lib/simple_validate/validates_length_of.rb', line 11

def initialize(attribute, options)
  super(attribute, options.delete(:message), options.delete(:if) ||
    proc { true })
  self.options = options
end

Instance Attribute Details

#attributeObject (readonly)

Returns the value of attribute attribute.



6
7
8
# File 'lib/simple_validate/validates_length_of.rb', line 6

def attribute
  @attribute
end

#optionsObject

Returns the value of attribute options.



7
8
9
# File 'lib/simple_validate/validates_length_of.rb', line 7

def options
  @options
end

Instance Method Details

#messageObject



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

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

#valid?(instance) ⇒ Boolean

Returns:

  • (Boolean)

Raises:

  • (ArgumentError)


49
50
51
52
53
54
55
56
57
58
# File 'lib/simple_validate/validates_length_of.rb', line 49

def valid?(instance)
  raise ArgumentError, "Only one length argument can be provided" if options.keys.size > 1

  unless VALID_LENGTH_OPTIONS.include?(options.keys.first)
    raise InvalidLengthOption, "Invalid length option given #{options.keys}"
  end

  actual_length = instance.send(attribute)&.length
  valid_length?(actual_length)
end

#valid_lengthObject



32
33
34
# File 'lib/simple_validate/validates_length_of.rb', line 32

def valid_length
  options.values.first
end

#valid_length?(actual_length) ⇒ Boolean

Returns:

  • (Boolean)


36
37
38
39
40
41
42
43
44
45
46
47
# File 'lib/simple_validate/validates_length_of.rb', line 36

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

#validatorObject



28
29
30
# File 'lib/simple_validate/validates_length_of.rb', line 28

def validator
  options.keys.first
end