Avro seriaization in ruby – Getting the serialized data as bytes within the program

The Avro ruby tutorials mention only about serializing to a file. This is how I managed to serialize into a blob within ruby.

Also, I found that in ruby we have to populate the object to be serialized as a Ruby Hash object matching the schema.

@SCHEMA = <<-JSON
{ “type”: “record”,
“name”: “LogEvent”,
“fields” : [
{“name”: “tag”, “type”: “string”},
{“name”: “time”, “type”: “long”},
{“name”: “record”, “type”: “string”}
]
}
JSON

schema = Avro::Schema.parse(@SCHEMA)
dw = Avro::IO::DatumWriter.new(schema)
buffer = StringIO.new(“”.force_encoding(“BINARY”))
encoder = Avro::IO::BinaryEncoder.new(buffer)
datum = Hash[“tag” =>tag, “time” => time, “record” => record[“message”]]
dw.write(datum, encoder)

The result will be available in buffer.

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s