Module: Forminate::ClientSideValidations

Extended by:
ActiveSupport::Concern
Defined in:
lib/forminate/client_side_validations.rb

Overview

This module makes Forminate work with bcardarella’s client_side_validations gem (github.com/bcardarella/client_side_validations).

The majority of the methods contained here are overrides or alternative versions of methods in the client_side_validations gem. For the most part, they follow the shape and ideas of the original implementation, usually adding the ability to send messages to an associated object rather than the Forminate object itself.

Instance Method Summary collapse

Instance Method Details

#client_side_validation_hash(force = nil) ⇒ Object

Where the magic happens. This overrides the client_side_validations gem’s method of the same name, using Forminate’s #association_validators rather than ActiveModel’s _validators method. It still calls super so that it includes validations placed directly on the Forminate object.



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
55
56
57
58
59
60
61
62
63
64
# File 'lib/forminate/client_side_validations.rb', line 25

def client_side_validation_hash(force = nil)
  hash = super
  assoc_hash = association_validators.reduce({}) do |assoc_hash, (attr, validators)|
    unless [nil, :block].include?(attr)

      validator_hash = validators.reduce(Hash.new { |h,k| h[k] = []}) do |kind_hash, validator|
        model = validator.target_object
        model_pattern = /^#{model.class.name.underscore}_/
        target_attr = attr.to_s.sub(model_pattern, '').to_sym

        if force.is_a? Hash
          relevant_force = force.select { |k, v| k.to_s.match model_pattern }
          assoc_force = relevant_force.reduce({}) do |assoc_force, (key, value)|
            key = key.to_s.sub(model_pattern, '').to_sym
            assoc_force.merge({ key => value })
          end
        else
          assoc_force = force
        end

        if _can_use_for_client_side_validation?(model, target_attr, validator, assoc_force)
          if client_side_hash = validator.client_side_hash(model, target_attr, extract_force_option(target_attr, assoc_force))
            kind_hash[validator.kind] << client_side_hash.except(:on, :if, :unless)
          end
        end

        kind_hash
      end

      if validator_hash.present?
        assoc_hash.merge!(attr => validator_hash)
      else
        assoc_hash
      end
    else
      assoc_hash
    end
  end
  hash.merge assoc_hash
end