Sha256: abfb09a8cc18b5de5f85e178102ca5a71cbe2563830b4a510a1cfe09c7d951b0

Contents?: true

Size: 1.99 KB

Versions: 3

Compression:

Stored size: 1.99 KB

Contents

# frozen_string_literal: true

require_relative 'base'
require 'json'

module Deimos
  module SchemaClass
    # Base Class of Record Classes generated from Avro.
    class Record < Base

      # Converts the object attributes to a hash which can be used for Kafka
      # @return [Hash] the payload as a hash.
      def to_h
        self.as_json
      end

      # Merge a hash or an identical schema object with this one and return a new object.
      # @param other_hash [Hash|SchemaClasses::Base]
      # @return [SchemaClasses::Base]
      def merge(other_hash)
        obj = self.class.new(**self.to_h.symbolize_keys)
        other_hash.to_h.each do |k, v|
          obj.send("#{k}=", v)
        end
        obj
      end

      # Element access method as if this Object were a hash
      # @param key[String||Symbol]
      # @return [Object] The value of the attribute if exists, nil otherwise
      def [](key)
        self.try(key.to_sym)
      end

      # :nodoc
      def with_indifferent_access
        self
      end

      # Returns the schema name of the inheriting class.
      # @return [String]
      def schema
        raise NotImplementedError
      end

      # Returns the namespace for the schema of the inheriting class.
      # @return [String]
      def namespace
        raise NotImplementedError
      end

      # Returns the full schema name of the inheriting class.
      # @return [String]
      def full_schema
        "#{namespace}.#{schema}"
      end

      # Returns the schema validator from the schema backend
      # @return [Deimos::SchemaBackends::Base]
      def validator
        Deimos.schema_backend(schema: schema, namespace: namespace)
      end

      # @return [Array<String>] an array of fields names in the schema.
      def schema_fields
        validator.schema_fields.map(&:name)
      end

      # :nodoc:
      def self.initialize_from_value(value)
        return nil if value.nil?

        value.is_a?(self) ? value : self.new(**value.symbolize_keys)
      end
    end
  end
end

Version data entries

3 entries across 3 versions & 1 rubygems

Version Path
deimos-ruby-1.16.2 lib/deimos/schema_class/record.rb
deimos-ruby-1.16.1 lib/deimos/schema_class/record.rb
deimos-ruby-1.16.0 lib/deimos/schema_class/record.rb