Class: Mixture::Validate::Length
- Defined in:
- lib/mixture/validate/length.rb
Overview
Validates the length of an attribute.
Instance Method Summary collapse
-
#acceptable ⇒ Range
Determines the acceptable range that the length ca nbe in.
-
#length ⇒ Numeric
Attempts to get the value of the length.
-
#to_hash(value) ⇒ Hash
Turns any other recoginizable value into a hash that #acceptable can use.
-
#validate(record, attribute, value) ⇒ void
Validates the length of the value.
Methods inherited from Base
Constructor Details
This class inherits a constructor from Mixture::Validate::Base
Instance Method Details
#acceptable ⇒ Range
If it is unable to find any of the options, or unable to turn the given value into a hash, it will raise a Mixture::ValidationError. This means validation will fail, even if the value may be valid.
Determines the acceptable range that the length ca nbe in. This first turns the options into a hash via #to_hash, and then checks the hash.
47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 |
# File 'lib/mixture/validate/length.rb', line 47 def acceptable @_acceptable ||= begin = to_hash(@options) if .key?(:in) then [:in] elsif .key?(:is) then [:is]..[:is] elsif .key?(:maximum) && .key?(:minimum) [:minimum]..[:maximum] elsif .key?(:maximum) then 0..[:maximum] elsif .key?(:minimum) then [:minimum]..Float::INFINITY else error("Unable to determine acceptable range") end end end |
#length ⇒ Numeric
Attempts to get the value of the length. It tries the
#size
, #length
, and finally, #count
; if it can't
find any of these, it raises an error.
98 99 100 101 102 103 104 |
# File 'lib/mixture/validate/length.rb', line 98 def length if @value.respond_to?(:size) then @value.size elsif @value.respond_to?(:length) then @value.length elsif @value.respond_to?(:count) then @value.count else error("Value isn't countable") end end |
#to_hash(value) ⇒ Hash
Turns any other recoginizable value into a hash that #acceptable can use. The mappings go as follows:
Range
: turns into{ in: value }
.Numeric
: turns into{ in: value..value }
Array
: turns into{ in: value[0]..value[1] }
Hash
: turns into itself.
Any other class/value causes an error.
80 81 82 83 84 85 86 87 88 89 |
# File 'lib/mixture/validate/length.rb', line 80 def to_hash(value) case value when Range then { in: value } when Numeric then { in: value..value } when Array then { in: value[0]..value[1] } when Hash then value else error("Unable to determine acceptable range") end end |
#validate(record, attribute, value) ⇒ void
This method returns an undefined value.
Validates the length of the value. It first composes an acceptable range, and then determines if the length is within that acceptable range. If either components error, the validation fails.
16 17 18 19 |
# File 'lib/mixture/validate/length.rb', line 16 def validate(record, attribute, value) super error("Length is not acceptable") unless acceptable.cover?(length) end |