Module: Avromatic::Model::Validation

Extended by:
ActiveSupport::Concern
Includes:
ActiveModel::Validations
Defined in:
lib/avromatic/model/validation.rb

Constant Summary collapse

EMPTY_ARRAY =
[].freeze

Class Method Summary collapse

Instance Method Summary collapse

Class Method Details

.missing_nested_attributes(attribute, value) ⇒ Object



11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
# File 'lib/avromatic/model/validation.rb', line 11

def self.missing_nested_attributes(attribute, value)
  if value.is_a?(Array)
    results = []
    value.each_with_index do |element, index|
      nested_results = missing_nested_attributes("#{attribute}[#{index}]", element)
      results.concat(nested_results)
    end
    results
  elsif value.is_a?(Hash)
    results = []
    value.each do |key, element|
      nested_results = missing_nested_attributes("#{attribute}['#{key}']", element)
      results.concat(nested_results)
    end
    results
  elsif value.respond_to?(:missing_avro_attributes)
    value.missing_avro_attributes.map do |missing_child_attribute|
      "#{attribute}.#{missing_child_attribute}"
    end
  else
    EMPTY_ARRAY
  end
end

Instance Method Details

#avro_validate!Object



44
45
46
47
48
49
50
# File 'lib/avromatic/model/validation.rb', line 44

def avro_validate!
  results = missing_avro_attributes
  if results.present?
    raise Avromatic::Model::ValidationError.new("#{self.class.name}(#{attributes.inspect}) cannot be " \
      "serialized because the following attributes are nil: #{results.join(', ')}")
  end
end

#missing_avro_attributesObject



52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
# File 'lib/avromatic/model/validation.rb', line 52

def missing_avro_attributes
  return @missing_attributes if instance_variable_defined?(:@missing_attributes)

  missing_attributes = []

  self.class.attribute_definitions.each_value do |attribute_definition|
    value = send(attribute_definition.name)
    field = attribute_definition.field
    if value.nil? && field.type.type_sym != :null && attribute_definition.required?
      missing_attributes << field.name
    else
      missing_attributes.concat(Avromatic::Model::Validation.missing_nested_attributes(field.name, value))
    end
  end

  @missing_attributes = missing_attributes.freeze if recursively_immutable?

  missing_attributes
end