Sha256: a61287b899cfc71946c24f0a8df45e1c1466d53251e65e63f5d504cd5faf938e
Contents?: true
Size: 1.54 KB
Versions: 2
Compression:
Stored size: 1.54 KB
Contents
module SimpleValidate class ValidatesLengthOf < ValidatesBase class InvalidLengthOption < ArgumentError; end attr_reader :attribute attr_accessor :options VALID_LENGTH_OPTIONS = %i[maximum minimum in is].freeze def initialize(attribute, options) super(attribute, options.delete(:message), options.delete(:if) || proc { true }) self.options = options end 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 def validator options.keys.first end def valid_length options.values.first end 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 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 end end
Version data entries
2 entries across 2 versions & 1 rubygems
Version | Path |
---|---|
simple_validate-1.2.2 | lib/simple_validate/validates_length_of.rb |
simple_validate-1.1.2 | lib/simple_validate/validates_length_of.rb |