lib/lutaml/model/serialize.rb in lutaml-model-0.3.3 vs lib/lutaml/model/serialize.rb in lutaml-model-0.3.4

- old
+ new

@@ -6,16 +6,19 @@ require_relative "mapping_rule" require_relative "mapping_hash" require_relative "xml_mapping" require_relative "key_value_mapping" require_relative "json_adapter" +require_relative "comparable_model" module Lutaml module Model module Serialize FORMATS = %i[xml json yaml toml].freeze + include ComparableModel + def self.included(base) base.extend(ClassMethods) end module ClassMethods @@ -48,27 +51,28 @@ define_method(name) do instance_variable_get(:"@#{name}") end define_method(:"#{name}=") do |value| - unless self.class.attr_value_valid?(name, value) - raise Lutaml::Model::InvalidValueError.new(name, value, options[:values]) - end - instance_variable_set(:"@#{name}", value) + validate end end # Check if the value to be assigned is valid for the attribute def attr_value_valid?(name, value) attr = attributes[name] return true unless attr.options[:values] - # If value validation failed but there is a default value, do not - # raise a validation error - attr.options[:values].include?(value || attr.default) + # Allow nil values if there's no default + return true if value.nil? && !attr.default + + # Use the default value if the value is nil + value = attr.default if value.nil? + + attr.options[:values].include?(value) end FORMATS.each do |format| define_method(format) do |&block| klass = format == :xml ? XmlMapping : KeyValueMapping @@ -401,10 +405,12 @@ self.class.attributes.each do |name, attr| value = self.class.attr_value(attrs, name, attr) send(:"#{name}=", self.class.ensure_utf8(value)) end + + validate end def ordered? @ordered end @@ -417,17 +423,27 @@ hash[key] || hash[key.to_sym] || hash[key.to_s] end FORMATS.each do |format| define_method(:"to_#{format}") do |options = {}| + validate adapter = Lutaml::Model::Config.public_send(:"#{format}_adapter") representation = if format == :xml self else self.class.hash_representation(self, format, options) end adapter.new(representation).public_send(:"to_#{format}", options) + end + end + + def validate + self.class.attributes.each do |name, attr| + value = send(name) + unless self.class.attr_value_valid?(name, value) + raise Lutaml::Model::InvalidValueError.new(name, value, attr.options[:values]) + end end end end end end