lib/avromatic/model/attributes.rb in avromatic-2.3.0 vs lib/avromatic/model/attributes.rb in avromatic-2.4.0
- old
+ new
@@ -25,11 +25,14 @@
delegate :serialize, to: :type
def initialize(owner:, field:, type:)
@owner = owner
@field = field
+ @required = FieldHelper.required?(field)
+ @nullable = FieldHelper.nullable?(field)
@type = type
+ @values_immutable = type.referenced_model_classes.all?(&:recursively_immutable?)
@name = field.name.to_sym
@name_string = field.name.to_s.dup.freeze
@setter_name = "#{field.name}=".to_sym
@default = if field.default == :no_default
nil
@@ -38,14 +41,22 @@
else
field.default
end
end
+ def nullable?
+ @nullable
+ end
+
def required?
- FieldHelper.required?(field)
+ @required
end
+ def values_immutable?
+ @values_immutable
+ end
+
def coerce(input)
type.coerce(input)
rescue Avromatic::Model::UnknownAttributeError => e
raise Avromatic::Model::CoercionError.new("Value for #{owner.name}##{name} could not be coerced to a #{type.name} " \
"because the following unexpected attributes were provided: #{e.unknown_attributes.join(', ')}. " \
@@ -67,10 +78,12 @@
end
included do
class_attribute :attribute_definitions, instance_writer: false
self.attribute_definitions = {}
+
+ delegate :recursively_immutable?, to: :class
end
def initialize(data = {})
super()
@@ -128,10 +141,16 @@
end
end
define_avro_attributes(avro_schema, generated_methods_module)
end
+ def recursively_immutable?
+ return @recursively_immutable if defined?(@recursively_immutable)
+
+ @recursively_immutable = immutable? && attribute_definitions.each_value.all?(&:values_immutable?)
+ end
+
private
def check_for_field_conflicts!
conflicts =
(key_avro_field_names & value_avro_field_names).each_with_object([]) do |name, msgs|
@@ -172,13 +191,13 @@
# Add all generated methods to a module so they can be overridden
generated_methods_module.send(:define_method, field.name) { _attributes[symbolized_field_name] }
generated_methods_module.send(:define_method, "#{field.name}?") { !!_attributes[symbolized_field_name] } if FieldHelper.boolean?(field)
generated_methods_module.send(:define_method, "#{field.name}=") do |value|
- _attributes[symbolized_field_name] = attribute_definitions[symbolized_field_name].coerce(value)
+ _attributes[symbolized_field_name] = attribute_definition.coerce(value)
end
- unless config.mutable # rubocop:disable Style/Next
+ unless mutable? # rubocop:disable Style/Next
generated_methods_module.send(:private, "#{field.name}=")
generated_methods_module.send(:define_method, :clone) { self }
generated_methods_module.send(:define_method, :dup) { self }
end
end