Module: Sinatra::Avro

Defined in:
lib/sinatra/avro.rb,
lib/sinatra/avro/version.rb

Constant Summary collapse

MIME_TYPE =
"avro/binary".freeze
VERSION =
"0.0.1"

Instance Method Summary collapse

Instance Method Details

#avro(object, options = {}) ⇒ Object



9
10
11
12
13
14
15
16
# File 'lib/sinatra/avro.rb', line 9

def avro(object, options = {})
  schema_json = fetch_avro_schema(options)

  # Set the Content-Type response header.
  content_type MIME_TYPE

  avro_encode(object, schema_json)
end

#avro_encode(object, schema_json) ⇒ Object



18
19
20
21
22
23
24
25
26
27
28
# File 'lib/sinatra/avro.rb', line 18

def avro_encode(object, schema_json)
  schema = ::Avro::Schema.parse(schema_json)
  writer = ::Avro::IO::DatumWriter.new(schema)
  io = StringIO.new

  dw = ::Avro::DataFile::Writer.new(io, writer, schema)
  dw << object.to_h
  dw.close

  io.string
end

#fetch_avro_schema(options = {}) ⇒ Object



30
31
32
# File 'lib/sinatra/avro.rb', line 30

def fetch_avro_schema(options = {})
  options[:schema] || load_avro_schema(options.fetch(:schema_name))
end

#load_avro_schema(schema_name) ⇒ Object



34
35
36
37
38
# File 'lib/sinatra/avro.rb', line 34

def load_avro_schema(schema_name)
  schema_path = File.join(settings.avro_schema_dir, schema_name + ".avsc")

  File.read(schema_path)
end