Class: SimpleValidate::ValidatesLengthOf
Defined Under Namespace
Classes: InvalidLengthOption
Constant Summary
collapse
- VALID_LENGTH_OPTIONS =
%i[maximum minimum in is].freeze
Instance Attribute Summary collapse
#condition
Instance Method Summary
collapse
Constructor Details
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
#attribute ⇒ Object
Returns the value of attribute attribute.
6
7
8
|
# File 'lib/simple_validate/validates_length_of.rb', line 6
def attribute
@attribute
end
|
#options ⇒ Object
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
#message ⇒ Object
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
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_length ⇒ Object
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
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
|
#validator ⇒ Object
28
29
30
|
# File 'lib/simple_validate/validates_length_of.rb', line 28
def validator
options.keys.first
end
|