Auro-serialization in Ruby - how to write in String / buffer instead of a file

I am trying to serialize avro in Ruby. I wrote a JSON schema, however I like to have serialized data as bytes in Ruby instead of writing to a file.

My code hangs something like:

SCHEMA = {
           "type": "record",
           "name": "User",
           "fields" :
             [
               {"name": "name", "type": "string"},
               {"name": "id", "type": "long"},
               {"name": "city", "type": "string"}
             ]
         }.to_json

schema = Avro::Schema.parse(SCHEMA)
dw = Avro::IO::DatumWriter.new(schema)
buffer = StringIO.new
encoder = Avro::IO::BinaryEncoder.new(buffer)
???

I have values ​​for the name, id and city and are wondering how to create a User object and serialize it in a string / byte buffer.

+4
source share
1 answer

It turned out:

schema = Avro::Schema.parse(SCHEMA)
dw = Avro::IO::DatumWriter.new(schema)
buffer = StringIO.new
encoder = Avro::IO::BinaryEncoder.new(buffer)
datum = Hash["name" =>name, "id" => id, "city" => city]
dw.write(datum, encoder)
Buffer

has resulting byte bytes in avro format.

It seems that Ruby does not yet have Avro client code. We must pass the data as Ruby hashes, as I did for the zero-scope field.

+4
source

Source: https://habr.com/ru/post/1526237/


All Articles