Class: CouchbaseOrm::PolymorphicTypeValidator

Inherits:
ActiveModel::EachValidator
  • Object
show all
Defined in:
lib/couchbase-orm/validators/polymorphic_type_validator.rb

Instance Method Summary collapse

Instance Method Details

#validate_each(record, attribute, value) ⇒ Object



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
# File 'lib/couchbase-orm/validators/polymorphic_type_validator.rb', line 5

def validate_each(record, attribute, value)
  allowed_types = options[:allowed_types]
  return if allowed_types.blank?
  return if value.nil?

  # Handle array of embedded objects
  if value.is_a?(Array)
    value.each_with_index do |obj, i|
      next if obj.nil?
      next if allowed_types.include?(obj.class.name)

      record.errors.add(
        attribute,
        "item ##{i} (#{obj.class.name}) is not an allowed type. Allowed types: #{allowed_types.join(', ')}"
      )
    end
  else
    # Handle single embedded object
    return if allowed_types.include?(value.class.name)

    record.errors.add(
      attribute,
      "#{value.class.name} is not an allowed type. Allowed types: #{allowed_types.join(', ')}"
    )
  end
end