Class: NeonSchemas::Avro

Inherits:
Object
  • Object
show all
Defined in:
lib/neon_schemas/avro.rb

Constant Summary collapse

SCHEMA_DIRECTORY =
"#{__dir__}/../../schemas"

Class Method Summary collapse

Class Method Details

.decode(string:, schema_name:) ⇒ Object



21
22
23
24
25
26
27
28
29
30
31
32
# File 'lib/neon_schemas/avro.rb', line 21

def self.decode(string:, schema_name:)
  avro_schema = ::Avro::Schema.parse(
    File.read("#{SCHEMA_DIRECTORY}/#{schema_name.tr(".", "/")}.avsc")
  )
  buffer = ::StringIO.new string
  decoder = ::Avro::IO::BinaryDecoder.new buffer
  reader = ::Avro::IO::DatumReader.new avro_schema

  json = reader.read(decoder).to_json

  JSON.parse(json, symbolize_names: true)
end

.encode(record:, schema_name:) ⇒ Object



8
9
10
11
12
13
14
15
16
17
18
19
# File 'lib/neon_schemas/avro.rb', line 8

def self.encode(record:, schema_name:)
  avro_schema = ::Avro::Schema.parse(
    File.read("#{SCHEMA_DIRECTORY}/#{schema_name.tr(".", "/")}.avsc")
  )
  writer = ::Avro::IO::DatumWriter.new avro_schema
  buffer = ::StringIO.new
  encoder = ::Avro::IO::BinaryEncoder.new buffer

  writer.write record, encoder

  buffer
end