Class: NYPLAvro
- Inherits:
-
Object
- Object
- NYPLAvro
- Defined in:
- lib/nypl_avro.rb
Direct Known Subclasses
Class Method Summary collapse
Instance Method Summary collapse
- #decode(encoded_data_string, base64 = true) ⇒ Object
- #encode(decoded_data, base64 = true) ⇒ Object
-
#initialize(schemaString) ⇒ NYPLAvro
constructor
A new instance of NYPLAvro.
Constructor Details
#initialize(schemaString) ⇒ NYPLAvro
9 10 11 12 13 14 15 16 17 |
# File 'lib/nypl_avro.rb', line 9 def initialize (schemaString) begin @schema = Avro::Schema.parse(schemaString) rescue Exception => e raise AvroError.new(e), "Failed to parse schema string: \"#{schemaString}\"" end @reader = Avro::IO::DatumReader.new(@schema) end |
Class Method Details
.by_name(name) ⇒ Object
49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 |
# File 'lib/nypl_avro.rb', line 49 def self.by_name (name) require 'net/http' require 'uri' uri = URI.parse("#{ENV["PLATFORM_API_BASE_URL"]}current-schemas/#{name}") begin response = Net::HTTP.get_response(uri) rescue Exception => e raise AvroError.new(e), "Failed to retrieve #{name} schema: #{e.message}" end begin response_hash = JSON.parse(response.body) rescue JSON::ParserError => e raise AvroError.new(e), "Retrieved #{name} schema is malformed: #{response.body}" end raise AvroError.new, "Failed to retrieve #{name} schema: statusCode=#{response_hash["statusCode"]}" if response_hash["statusCode"] >= 400 raise AvroError.new, "Retrieved #{name} schema is malformed" if response_hash["data"].nil? || response_hash["data"]["schema"].nil? self.new response_hash["data"]["schema"] end |
Instance Method Details
#decode(encoded_data_string, base64 = true) ⇒ Object
19 20 21 22 23 24 25 26 27 28 29 30 |
# File 'lib/nypl_avro.rb', line 19 def decode(encoded_data_string, base64 = true) avro_string = base64 ? Base64.decode64(encoded_data_string) : encoded_data_string stringreader = StringIO.new(avro_string) bin_decoder = Avro::IO::BinaryDecoder.new(stringreader) begin read_value = @reader.read(bin_decoder) rescue Exception => e raise AvroError.new(e), "Error decoding data using #{@schema.name} schema" end read_value end |
#encode(decoded_data, base64 = true) ⇒ Object
32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 |
# File 'lib/nypl_avro.rb', line 32 def encode(decoded_data, base64 = true) bin_encoder = Avro::IO::DatumWriter.new(@schema) buffer = StringIO.new buffer.set_encoding('UTF-8') encoder = Avro::IO::BinaryEncoder.new(buffer) begin bin_encoder.write(decoded_data, encoder) rescue Avro::IO::AvroTypeError => e raise AvroError.new(e), "Error encoding data #{decoded_data} using #{@schema.name} schema due to #{e.message}" end buffer.rewind result = buffer.read base64 ? Base64.encode64(result) : result end |