lib/avromatic/model/attribute/union.rb in avromatic-0.13.0 vs lib/avromatic/model/attribute/union.rb in avromatic-0.14.0.rc0
- old
+ new
@@ -1,6 +1,7 @@
require 'avromatic/model/attribute_type/union'
+require 'avromatic/io/datum_reader'
module Avromatic
module Model
module Attribute
@@ -10,10 +11,12 @@
# member types, and then by attempting to coerce to each member type in
# order.
class Union < Virtus::Attribute
primitive Avromatic::Model::AttributeType::Union
+ MEMBER_INDEX = ::Avromatic::IO::DatumReader::UNION_MEMBER_INDEX
+
def initialize(*)
super
primitive.types.each do |type|
member_attributes << Virtus::Attribute.build(type)
@@ -22,16 +25,15 @@
def coerce(input)
return input if value_coerced?(input)
result = nil
- member_attributes.find do |union_attribute|
- begin
- coerced = union_attribute.coerce(input)
- result = coerced unless coerced.is_a?(Avromatic::Model::Attributes) && coerced.invalid?
- rescue
- nil
+ if input.key?(MEMBER_INDEX)
+ result = safe_coerce(member_attributes[input.delete(MEMBER_INDEX)], input)
+ else
+ member_attributes.find do |union_attribute|
+ result = safe_coerce(union_attribute, input)
end
end
result
end
@@ -40,9 +42,16 @@
union_attribute.value_coerced?(value)
end
end
private
+
+ def safe_coerce(member_attribute, input)
+ coerced = member_attribute.coerce(input)
+ coerced unless coerced.is_a?(Avromatic::Model::Attributes) && coerced.invalid?
+ rescue
+ nil
+ end
def member_attributes
@member_attributes ||= Array.new
end
end