class Kril::SchemaHandler

Saves schemas to repository.

Public Class Methods

new(schemas_path:, schema_store: nil) click to toggle source

schemas_path - directory of schema repository [String] schema_store - schema store [AvroTurf::SchemaStore]

# File lib/kril/schema_handler.rb, line 8
def initialize(schemas_path:,
               schema_store: nil)
  schema_store ||= AvroTurf::SchemaStore.new(path: schemas_path)
  @schema_store = schema_store
  @schemas_path = schemas_path
end

Public Instance Methods

process(input_string) click to toggle source

Handles input to reference or create schema.

input_string - schema name, schema file, or schema contents [String] returns - stored schema [Avro::Schema]

# File lib/kril/schema_handler.rb, line 19
def process(input_string)
  return nil unless input_string
  name, namespace =
    if File.exist?(input_string)
      copy_schema_to_store(input_string)
    elsif schema?(input_string)
      save_schema(input_string)
    else
      separate_fullname(input_string)
    end
  @schema_store.find(name, namespace)
end

Private Instance Methods

build_path(name, namespace) click to toggle source
# File lib/kril/schema_handler.rb, line 48
def build_path(name, namespace)
  base = namespace ? File.join(@schemas_path, namespace.split('.')) : @schemas_path
  File.join(base, "#{name}.avsc")
end
copy_schema_to_store(path) click to toggle source
# File lib/kril/schema_handler.rb, line 63
def copy_schema_to_store(path)
  schema = File.read(path)
  raise ArgumentError, "Not a valid schema: #{path}" unless schema?(schema)
  save_schema(schema)
end
save_schema(schema) click to toggle source
# File lib/kril/schema_handler.rb, line 53
def save_schema(schema)
  schema = JSON.parse(schema)
  path = build_path(schema['name'], schema['namespace'])
  FileUtils.mkdir_p(File.dirname(path))
  File.open(path, 'w') do |file|
    file.write(JSON.pretty_generate(schema))
  end
  [schema['name'], schema['namespace']]
end
schema?(input) click to toggle source
# File lib/kril/schema_handler.rb, line 42
def schema?(input)
  !JSON.parse(input)['name'].nil?
rescue StandardError
  false
end
separate_fullname(fullname) click to toggle source
# File lib/kril/schema_handler.rb, line 34
def separate_fullname(fullname)
  arr = fullname.split('.')
  name = arr.pop
  namespace = arr.join('.')
  namespace = nil if namespace.empty?
  [name, namespace]
end