Sha256: e9f93e31e8d9fa79c68ca15cf93cf9faa8a739cd38e27143f64e15cdb1beb184
Contents?: true
Size: 1.64 KB
Versions: 2
Compression:
Stored size: 1.64 KB
Contents
module SimpleValidate class ValidatesLengthOf attr_reader :attribute class InvalidLengthOption < ArgumentError; end VALID_LENGTH_OPTIONS = %i(maximum minimum in is) def initialize(attribute, options) @message = options.delete(:message) @attribute = attribute @options = options check_options(@options) @length_validator = @options.select { |k, _| VALID_LENGTH_OPTIONS.include?(k) } end def message @message ||= begin case @length_validator.keys.first when :minimum 'is too short' when :maximum 'is too long' else 'is not the correct length' end end end def validator @options.entries.first end def check_options(options) if options.keys.size > 1 || !VALID_LENGTH_OPTIONS.include?(options.keys.first) raise InvalidLengthOption, "Invalid length option given #{@options.keys}" end end def valid_length?(actual_length) validator_key, valid_length = @length_validator.entries.first case validator_key when :minimum actual_length >= valid_length ? true : false when :maximum actual_length <= valid_length ? true : false when :in valid_length.member?(actual_length) ? true : false when :is actual_length == valid_length ? true : false end end def valid?(instance) actual_length = instance.send(attribute).length valid_length?(actual_length) end end end
Version data entries
2 entries across 2 versions & 1 rubygems
Version | Path |
---|---|
simple_validate-1.1.0 | lib/simple_validate/validates_length_of.rb |
simple_validate-1.0.0 | lib/simple_validate/validates_length_of.rb |