Module: AvroGen::SchemaClass

Defined in:
lib/avro_gen/schema_class.rb,
lib/avro_gen/schema_class/base.rb,
lib/avro_gen/schema_class/enum.rb,
lib/avro_gen/schema_class/record.rb

Overview

Helpers used by the generator and by consumer/producer interfaces to locate and instantiate generated schema classes.

Defined Under Namespace

Classes: Base, Enum, Record

Class Method Summary collapse

Class Method Details

.instance(payload, schema, namespace = '') ⇒ AvroGen::SchemaClass::Record

Converts a raw payload into an instance of the Schema Class

Parameters:

Returns:



43
44
45
46
47
48
49
50
# File 'lib/avro_gen/schema_class.rb', line 43

def instance(payload, schema, namespace='')
  return payload if payload.is_a?(AvroGen::SchemaClass::Base)

  klass = klass(schema, namespace)
  return payload if klass.nil? || payload.nil?

  klass.new_from_message(**payload.symbolize_keys)
end

.klass(schema, namespace) ⇒ Class?

Determine and return the SchemaClass with the provided schema and namespace

Parameters:

  • schema (String)
  • namespace (String)

Returns:

  • (Class, nil)


56
57
58
59
# File 'lib/avro_gen/schema_class.rb', line 56

def klass(schema, namespace)
  constants = modules_for(namespace) + [schema.underscore.camelize.singularize]
  constants.join('::').safe_constantize
end

.modules_for(namespace) ⇒ Array<String>

Parameters:

  • namespace (String)

Returns:

  • (Array<String>)


14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
# File 'lib/avro_gen/schema_class.rb', line 14

def modules_for(namespace)
  modules = [AvroGen.config.root_module]
  namespace_override = nil
  module_namespace = namespace

  if AvroGen.config.use_full_namespace
    if AvroGen.config.schema_namespace_map.present?
      namespace_keys = AvroGen.config.schema_namespace_map.keys.sort_by { |k| -k.length }
      namespace_override = namespace_keys.find { |k| module_namespace.include?(k) }
    end

    if namespace_override.present?
      # override default module
      modules = Array(AvroGen.config.schema_namespace_map[namespace_override])
      module_namespace = module_namespace.gsub(/#{namespace_override}\.?/, '')
    end

    namespace_folders = module_namespace.split('.').map { |f| f.underscore.camelize }
    modules.concat(namespace_folders) if namespace_folders.any?
  end

  modules
end