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
27
28
|
# File 'lib/simple_validate/validates_length_of.rb', line 17
def message
@message ||= begin
case validator
when :minimum
'is too short'
when :maximum
'is too long'
else
'is not the correct length'
end
end
end
|
#valid?(instance) ⇒ Boolean
51
52
53
54
55
56
57
58
59
60
61
62
|
# File 'lib/simple_validate/validates_length_of.rb', line 51
def valid?(instance)
if options.keys.size > 1
raise ArgumentError, 'Only one length argument can be provided'
end
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
34
35
36
|
# File 'lib/simple_validate/validates_length_of.rb', line 34
def valid_length
options.values.first
end
|
#valid_length?(actual_length) ⇒ Boolean
38
39
40
41
42
43
44
45
46
47
48
49
|
# File 'lib/simple_validate/validates_length_of.rb', line 38
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
30
31
32
|
# File 'lib/simple_validate/validates_length_of.rb', line 30
def validator
options.keys.first
end
|