# Copyright 2011-2012 Amazon.com, Inc. or its affiliates. All Rights Reserved.## Licensed under the Apache License, Version 2.0 (the "License"). You# may not use this file except in compliance with the License. A copy of# the License is located at## http://aws.amazon.com/apache2.0/## or in the "license" file accompanying this file. This file is# distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF# ANY KIND, either express or implied. See the License for the specific# language governing permissions and limitations under the License.require'aws/record/validator'moduleAWSmoduleRecord# @privateclassLengthValidator<ValidatorACCEPTED_OPTIONS=[:exactly,:within,:minimum,:maximum,:too_long,:too_short,:wrong_length,:allow_nil,:on,:if,:unless,]defsetuprecord_classensure_at_least_one(:within,:exactly,:minimum,:maximum)ensure_exclusive(:within,:exactly,[:minimum,:maximum])ensure_type(Range,:within)ensure_type(Integer,:exactly,:minimum,:maximum)ensure_type(String,:too_long,:too_short,:wrong_length)enddefvalidate_attributerecord,attribute_name,value_or_valueseach_value(value_or_values)do|value|length=value.respond_to?(:length)?value.length:value.to_s.lengthifexact=options[:exactly]unlesslength==exactrecord.errors.add(attribute_name,wrong_length(exact,length))endendifwithin=options[:within]iflength<within.firstrecord.errors.add(attribute_name,too_short(within.first,length))endiflength>within.lastrecord.errors.add(attribute_name,too_long(within.last,length))endendifmin=options[:minimum]iflength<minrecord.errors.add(attribute_name,too_short(min,length))endendifmax=options[:maximum]iflength>maxrecord.errors.add(attribute_name,too_long(max,length))endendendend# @privateprotecteddefwrong_lengthexactly,gotmsg=options[:wrong_length]||"is the wrong length (should be %{exactly} characters)"interpolate(msg,:exactly=>exactly,:length=>got)end# @privateprotecteddeftoo_shortmin,gotmsg=options[:too_short]||"is too short (minimum is %{minimum} characters)"interpolate(msg,:minimum=>min,:length=>got)end# @privateprotecteddeftoo_longmax,gotmsg=options[:too_long]||"is too long (maximum is %{maximum} characters)"interpolate(msg,:maximum=>max,:length=>got)endprotecteddefinterpolatemessage_with_placeholders,valuesmsg=message_with_placeholders.dupvalues.each_pairdo|key,value|msg.gsub!(/%\{#{key}\}/,value.to_s)endmsgendendendend