Sha256: 957ec969f6596a88e7d41e6f606dc62b5e5108c9791b207b2384d723e2237faf

Contents?: true

Size: 771 Bytes

Versions: 3

Compression:

Stored size: 771 Bytes

Contents

module Validatable 
  class ValidatesNumericalityOf < ValidationBase #:nodoc:
    option :only_integer
    
    def valid?(instance)
      value = value_for(instance)
      return true if allow_nil && value.nil?
      return true if allow_blank && value.blank?
      
      value = value.to_s
      regex = self.only_integer ? /\A[+-]?\d+\Z/ : /\A[+-]?\d*\.{0,1}\d+$/
      not (value =~ regex).nil?
    end
    
    def message(instance)
      super || "must be a number"
    end
    
    private
      def value_for(instance)
        before_typecast_method = "#{self.attribute}_before_typecast"
        value_method = instance.respond_to?(before_typecast_method.intern) ? before_typecast_method : self.attribute
        instance.send(value_method)
      end
  end
end

Version data entries

3 entries across 3 versions & 2 rubygems

Version Path
lgustafson-validatable-1.8.7 lib/validatable/validations/validates_numericality_of.rb
lgustafson-validatable-1.8.6 lib/validatable/validations/validates_numericality_of.rb
np422-validatable-1.8.5 lib/validatable/validations/validates_numericality_of.rb