Class: Avromatic::IO::DatumWriter

Inherits:
Avro::IO::DatumWriter
  • Object
show all
Defined in:
lib/avromatic/io/datum_writer.rb

Overview

Subclass DatumWriter to use additional information about union member index.

Instance Method Summary collapse

Instance Method Details

#write_record(writers_schema, datum, encoder) ⇒ Object



24
25
26
27
28
29
30
# File 'lib/avromatic/io/datum_writer.rb', line 24

def write_record(writers_schema, datum, encoder)
  if datum.is_a?(Hash) && datum.key?(Avromatic::IO::ENCODING_PROVIDER)
    encoder.write(datum[Avromatic::IO::ENCODING_PROVIDER].avro_raw_value)
  else
    super
  end
end

#write_union(writers_schema, datum, encoder) ⇒ Object



6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
# File 'lib/avromatic/io/datum_writer.rb', line 6

def write_union(writers_schema, datum, encoder)
  optional = writers_schema.schemas.first.type_sym == :null
  if datum.is_a?(Hash) && datum.key?(Avromatic::IO::UNION_MEMBER_INDEX)
    index_of_schema = datum[Avromatic::IO::UNION_MEMBER_INDEX]
    # Avromatic does not treat the null of an optional field as part of the union
    index_of_schema += 1 if optional
  else
    index_of_schema = writers_schema.schemas.find_index do |schema|
      Avro::Schema.validate(schema, datum)
    end
  end
  unless index_of_schema
    raise Avro::IO::AvroTypeError.new(writers_schema, datum)
  end
  encoder.write_long(index_of_schema)
  write_data(writers_schema.schemas[index_of_schema], datum, encoder)
end