File: numericality.rb

package info (click to toggle)
ruby-client-side-validations 23.1.0-1
  • links: PTS, VCS
  • area: main
  • in suites: sid
  • size: 272 kB
  • sloc: ruby: 788; javascript: 671; makefile: 2
file content (54 lines) | stat: -rw-r--r-- 1,466 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
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
# frozen_string_literal: true

module ClientSideValidations
  module ActiveModel
    module Numericality
      @@option_map = {}

      def self.included(base)
        checks = base::RESERVED_OPTIONS - [:only_integer]

        @@option_map.merge!(checks.inject({}) { |acc, elem| acc.merge!(elem => elem) })
        super
      end

      def client_side_hash(model, attribute, force = nil)
        options = self.options.dup
        hash    = options_hash(model, attribute, options)

        @@option_map.each do |option, message_type|
          count = options[option]
          next unless count

          if count.respond_to?(:call)
            next unless force

            count = resolve_proc(count, model)
          end

          hash[:messages][option] = model.errors.generate_message(attribute, message_type, options.merge(count: count))
          hash[option] = count
        end

        copy_conditional_attributes(hash, options)

        hash
      end

      private

      def options_hash(model, attribute, options)
        hash = { messages: { numericality: model.errors.generate_message(attribute, :not_a_number, options) } }

        if options[:only_integer]
          hash[:messages][:only_integer] = model.errors.generate_message(attribute, :not_an_integer, options)
          hash[:only_integer] = true
        end

        hash[:allow_blank] = true if options[:allow_nil] || options[:allow_blank]

        hash
      end
    end
  end
end