Class: Avromatic::Model::Attribute::Union
- Inherits:
-
Virtus::Attribute
- Object
- Virtus::Attribute
- Avromatic::Model::Attribute::Union
- Defined in:
- lib/avromatic/model/attribute/union.rb
Overview
This subclass of Virtus::Attribute is used for any unions that are defined as subclasses of the primitive Avromatic::Model::AttributeType::Union. Values are coerced by first checking if they already match one of the member types, and then by attempting to coerce to each member type in order.
Constant Summary collapse
- MEMBER_INDEX =
::Avromatic::IO::DatumReader::UNION_MEMBER_INDEX
Instance Method Summary collapse
- #coerce(input) ⇒ Object
-
#initialize ⇒ Union
constructor
A new instance of Union.
- #value_coerced?(value) ⇒ Boolean
Constructor Details
#initialize ⇒ Union
Returns a new instance of Union.
18 19 20 21 22 23 24 |
# File 'lib/avromatic/model/attribute/union.rb', line 18 def initialize(*) super primitive.types.each do |type| member_attributes << Virtus::Attribute.build(type) end end |
Instance Method Details
#coerce(input) ⇒ Object
26 27 28 29 30 31 32 33 34 35 36 37 38 |
# File 'lib/avromatic/model/attribute/union.rb', line 26 def coerce(input) return input if value_coerced?(input) result = nil if input && 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 |
#value_coerced?(value) ⇒ Boolean
40 41 42 43 44 |
# File 'lib/avromatic/model/attribute/union.rb', line 40 def value_coerced?(value) member_attributes.any? do |union_attribute| union_attribute.value_coerced?(value) end end |