File: numericality.rb

package info (click to toggle)
rails 2%3A6.1.7.10%2Bdfsg-1~deb12u1
  • links: PTS, VCS
  • area: main
  • in suites: bookworm
  • size: 39,756 kB
  • sloc: ruby: 290,662; javascript: 19,241; yacc: 46; sql: 43; makefile: 32; sh: 18
file content (35 lines) | stat: -rw-r--r-- 1,424 bytes parent folder | download
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
# frozen_string_literal: true

module ActiveRecord
  module Validations
    class NumericalityValidator < ActiveModel::Validations::NumericalityValidator # :nodoc:
      def validate_each(record, attribute, value, precision: nil, scale: nil)
        precision = [column_precision_for(record, attribute) || Float::DIG, Float::DIG].min
        scale     = column_scale_for(record, attribute)
        super(record, attribute, value, precision: precision, scale: scale)
      end

      private
        def column_precision_for(record, attribute)
          record.class.type_for_attribute(attribute.to_s)&.precision
        end

        def column_scale_for(record, attribute)
          record.class.type_for_attribute(attribute.to_s)&.scale
        end
    end

    module ClassMethods
      # Validates whether the value of the specified attribute is numeric by
      # trying to convert it to a float with Kernel.Float (if <tt>only_integer</tt>
      # is +false+) or applying it to the regular expression <tt>/\A[\+\-]?\d+\z/</tt>
      # (if <tt>only_integer</tt> is set to +true+). Kernel.Float precision
      # defaults to the column's precision value or 15.
      #
      # See ActiveModel::Validations::HelperMethods.validates_numericality_of for more information.
      def validates_numericality_of(*attr_names)
        validates_with NumericalityValidator, _merge_attributes(attr_names)
      end
    end
  end
end