Module: ActiveModel::Validations::ClassMethods

Defined in:
lib/optional_validations.rb

Instance Method Summary collapse

Instance Method Details

#__validates_withObject



8
# File 'lib/optional_validations.rb', line 8

alias_method :__validates_with, :validates_with

#validates_with(*args, &block) ⇒ Object



9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
# File 'lib/optional_validations.rb', line 9

def validates_with(*args, &block)

  _if = Array(args[1][:if])

  # if multiple attribute names are supplied we need to split them into separate validates_with calls
  # in order to be able to choose only relevant validations to certain fields
  args[1][:attributes].each do |attr_name|
    args[1][:attributes] = [attr_name]
    args[1][:if] = _if.clone
    args[1][:if].unshift -> do
      if @__validate_only.present?
        @__validate_only.include?(attr_name)
      elsif @__validate_except.present?
        ! @__validate_except.include?(attr_name)
      else
        true
      end
    end
    __validates_with(*args, &block)
  end
end