Module: Avromatic::Model::Attributes

Extended by:
ActiveSupport::Concern
Defined in:
lib/avromatic/model/attributes.rb

Overview

This module supports defining Virtus attributes for a model based on the fields of Avro schemas.

Defined Under Namespace

Modules: ClassMethods Classes: AttributeDefinition, OptionalFieldError

Instance Method Summary collapse

Instance Method Details

#initialize(data = {}) ⇒ Object



98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
# File 'lib/avromatic/model/attributes.rb', line 98

def initialize(data = {})
  super()

  num_valid_keys = 0
  attribute_definitions.each do |attribute_name, attribute_definition|
    if data.include?(attribute_name)
      num_valid_keys += 1
      value = data.fetch(attribute_name)
      send(attribute_definition.setter_name, value)
    elsif data.include?(attribute_definition.name_string)
      num_valid_keys += 1
      value = data[attribute_definition.name_string]
      send(attribute_definition.setter_name, value)
    elsif !_attributes.include?(attribute_name)
      send(attribute_definition.setter_name, attribute_definition.default)
    end
  end

  unless Avromatic.allow_unknown_attributes || num_valid_keys == data.size
    unknown_attributes = (data.keys.map(&:to_s) - _attributes.keys.map(&:to_s)).sort
    allowed_attributes = attribute_definitions.keys.map(&:to_s).sort
    message = "Unexpected arguments for #{self.class.name}#initialize: #{unknown_attributes.join(', ')}. " \
      "Only the following arguments are allowed: #{allowed_attributes.join(', ')}. " \
      "Provided arguments: #{data.inspect}"
    raise Avromatic::Model::UnknownAttributeError.new(message, unknown_attributes: unknown_attributes,
                                                      allowed_attributes: allowed_attributes)
  end
end

#to_hObject Also known as: to_hash, attributes



127
128
129
# File 'lib/avromatic/model/attributes.rb', line 127

def to_h
  _attributes.dup
end