Sha256: f58c63e3de4f5ee4ba1b4d49f4e83567109ac1232bea32bf073f9717c092c2fc

Contents?: true

Size: 1.64 KB

Versions: 39

Compression:

Stored size: 1.64 KB

Contents

require 'active_support/core_ext/string/access'

module Avromatic
  # The ModelRegistry class is used to store and fetch nested models by
  # their fullname. An optional namespace prefix can be removed from the full
  # name that is used to store and fetch models.
  class ModelRegistry

    def initialize(remove_namespace_prefix: nil)
      @prefix = remove_namespace_prefix
      @hash = Hash.new
    end

    def clear
      @hash.clear
    end

    def [](fullname)
      @hash.fetch(fullname)
    end
    alias_method :fetch, :[]

    def register(model)
      raise 'models with a key schema are not supported' if model.key_avro_schema
      name = model_fullname(model)
      raise "'#{name}' has already been registered" if registered?(name)
      @hash[name] = model
    end

    def registered?(fullname)
      @hash.key?(fullname)
    end

    def model_fullname(model)
      name = model.avro_schema.fullname
      remove_prefix(name)
    end

    def ensure_registered_model(model)
      name = model_fullname(model)
      if registered?(name)
        unless fetch(name).equal?(model)
          raise "attempted to replace existing model #{fetch(name)} with new model #{model} as '#{name}'"
        end
      else
        register(model)
      end
    end

    def remove_prefix(name)
      return name if @prefix.nil?

      value =
        case @prefix
        when String
          name.start_with?(@prefix) ? name.from(@prefix.length) : name
        when Regexp
          name.sub(@prefix, '')
        else
          raise "unsupported `remove_namespace_prefix` value: #{@prefix}"
        end

      value.start_with?('.') ? value.from(1) : value
    end
  end
end

Version data entries

39 entries across 39 versions & 1 rubygems

Version Path
avromatic-1.0.0 lib/avromatic/model_registry.rb
avromatic-0.33.0 lib/avromatic/model_registry.rb
avromatic-0.32.0 lib/avromatic/model_registry.rb
avromatic-0.32.0.rc0 lib/avromatic/model_registry.rb
avromatic-0.31.0 lib/avromatic/model_registry.rb
avromatic-0.30.0 lib/avromatic/model_registry.rb
avromatic-0.29.1 lib/avromatic/model_registry.rb
avromatic-0.29.0 lib/avromatic/model_registry.rb
avromatic-0.28.1 lib/avromatic/model_registry.rb
avromatic-0.27.0 lib/avromatic/model_registry.rb
avromatic-0.26.0 lib/avromatic/model_registry.rb
avromatic-0.25.0 lib/avromatic/model_registry.rb
avromatic-0.24.0 lib/avromatic/model_registry.rb
avromatic-0.23.0 lib/avromatic/model_registry.rb
avromatic-0.22.0 lib/avromatic/model_registry.rb
avromatic-0.21.1 lib/avromatic/model_registry.rb
avromatic-0.21.0 lib/avromatic/model_registry.rb
avromatic-0.21.0.rc1 lib/avromatic/model_registry.rb
avromatic-0.21.0.rc0 lib/avromatic/model_registry.rb
avromatic-0.20.0 lib/avromatic/model_registry.rb