# 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# @privateclassNumericalityValidator<ValidatorACCEPTED_OPTIONS=[:greater_than,:greater_than_or_equal_to,:less_than,:less_than_or_equal_to,:equal_to,:only_integer,:odd,:even,:message,:allow_nil,:on,:if,:unless,]COMPARISONS={:equal_to=>:==,:greater_than=>:>,:greater_than_or_equal_to=>:>=,:less_than=>:<,:less_than_or_equal_to=>:<=,:even=>lambda{|value|value.to_i%2==0},:odd=>lambda{|value|value.to_i%2==1},}defsetuprecord_classensure_exclusive(:odd,:even)ensure_exclusive(:equal_to,[:greater_than,:greater_than_or_equal_to,:less_than,:less_than_or_equal_to])ensure_type([TrueClass,FalseClass],:only_integer)ensure_type(TrueClass,:odd,:even)ensure_type([Numeric,Symbol,Proc],:greater_than,:greater_than_or_equal_to,:less_than,:less_than_or_equal_to,:equal_to)enddefread_attribute_for_validation(record,attribute_name)ifrecord.respond_to?("#{attribute_name}_before_type_cast")record.send("#{attribute_name}_before_type_cast")elserecord.send(attribute_name)endenddefvalidate_attributerecord,attribute_name,raweach_value(raw)do|raw_value|ifoptions[:only_integer]oroptions[:odd]oroptions[:even]value=as_integer(raw_value)error_type=:not_an_integerelsevalue=as_number(raw_value)error_type=:not_a_numberendunlessvaluerecord.errors.add(attribute_name,message_for(error_type))returnendCOMPARISONS.eachdo|option,method|nextunlessoptions.has_key?(option)requirement=caseoptions[option]whenSymbolthenrecord.send(options[option])whenProcthenoptions[option].call(record)elseoptions[option]endvalid=casemethodwhenSymbolthenvalue.send(method,requirement)elsemethod.call(value)endunlessvalidmessage=message_for(option,requirement)record.errors.add(attribute_name,message)endendendenddefmessage_forerror_type,requirement=nilreturnoptions[:message]ifoptions[:message]caseerror_typewhen:not_a_numberthen'is not a number'when:not_an_integerthen'must be an integer'when:eventhen'must be an even number'when:oddthen'must be an odd number'when:equal_tothen"should equal #{requirement}"else"must be #{error_type.to_s.gsub(/_/,' ')}#{requirement}"endenddefas_numbervaluebeginKernel.Float(value)rescueArgumentError,TypeErrornilendenddefas_integervaluebeginKernel.Integer(value)rescueArgumentError,TypeErrornilendendendendend