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
- #initialize(data = {}) ⇒ Object
- #to_h ⇒ Object (also: #to_hash, #attributes)
Instance Method Details
#initialize(data = {}) ⇒ Object
74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 |
# File 'lib/avromatic/model/attributes.rb', line 74 def initialize(data = {}) super() valid_keys = [] attribute_definitions.each do |attribute_name, attribute_definition| if data.include?(attribute_name) valid_keys << attribute_name value = data.fetch(attribute_name) send(attribute_definition.setter_name, value) elsif data.include?(attribute_definition.name_string) valid_keys << attribute_name 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 || valid_keys.size == data.size unknown_attributes = (data.keys.map(&:to_s) - valid_keys.map(&:to_s)).sort allowed_attributes = attribute_definitions.keys.map(&:to_s).sort = "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(, unknown_attributes: unknown_attributes, allowed_attributes: allowed_attributes) end end |
#to_h ⇒ Object Also known as: to_hash, attributes
102 103 104 |
# File 'lib/avromatic/model/attributes.rb', line 102 def to_h _attributes.dup end |