Class: SimpleValidate::ValidatesLengthOf
- Inherits:
-
ValidatesBase
- Object
- ValidatesBase
- SimpleValidate::ValidatesLengthOf
- 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
Instance Method Summary collapse
-
#initialize(attribute, options) ⇒ ValidatesLengthOf
constructor
A new instance of ValidatesLengthOf.
- #message ⇒ Object
- #valid?(instance) ⇒ Boolean
- #valid_length?(actual_length) ⇒ Boolean
Constructor Details
#initialize(attribute, options) ⇒ ValidatesLengthOf
Returns a new instance of ValidatesLengthOf.
7 8 9 10 11 12 13 14 15 16 |
# File 'lib/simple_validate/validates_length_of.rb', line 7 def initialize(attribute, ) @validator = .keys.first raise ArgumentError, "Invalid length option" unless VALIDATORS.include?(@validator) @valid_length = [@validator] @allow_nil = [:allow_nil] super(attribute, [:message], [:if] || proc { true }) end |
Instance Method Details
#message ⇒ Object
18 19 20 21 22 23 24 25 26 27 |
# File 'lib/simple_validate/validates_length_of.rb', line 18 def = case @validator when :minimum "is too short" when :maximum "is too long" else "is not valid length" end end |
#valid?(instance) ⇒ 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
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 |