Class: ActiveModelExtensions::Validations::CustomPresenceValidator

Inherits:
ActiveModel::Validator
  • Object
show all
Defined in:
lib/rails_core_extensions/active_model_extensions.rb

Overview

The string is a CSV of required field rules, where each field rule is:

- the name of a required field
- OR a set of required field names spearated by 'or' (where only ONE is required)

Instance Method Summary collapse

Instance Method Details

#validate(record) ⇒ Object



19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
# File 'lib/rails_core_extensions/active_model_extensions.rb', line 19

def validate(record)
  required_fields = Array.wrap(@options[:attributes]).first.call || []
  return if required_fields.empty?

  required_fields.flatten.each do |required_field|
    if required_field.include? ' or '
      fields = required_field.split(' or ')
      if fields.all? { |field| record.send(field).to_s.blank? }
        record.errors.add(:base, "One of %s is required" % fields.map(&:humanize).to_sentence)
      end
    else
      if record.send(required_field).to_s.blank?
        record.errors.add(required_field, "is required")
      end
    end
  end

end