Sha256: 5a8b165bf63c85237be59ecdc31907dcb4d8d204b7796ca8f060dba8d5803fa9

Contents?: true

Size: 1.8 KB

Versions: 1

Compression:

Stored size: 1.8 KB

Contents

require 'vagrant/errors'

module ConfigBuilder

  # This defines a registry for classes, and behaves as a factory for registered classes.
  #
  # @api private
  class ClassRegistry

    class UnknownEntry < Vagrant::Errors::VagrantError
      error_key('unknown_entry', 'config_builder.class_registry')
    end

    class DuplicateEntry < Vagrant::Errors::VagrantError
      error_key('duplicate_entry', 'config_builder.class_registry')
    end

    def initialize(name)
      @name    = name
      @klasses = {}
    end

    # Register a class with a given identifier
    #
    # @param identifier [Symbol]
    # @param klass [Class]
    #
    # @return [void]
    def register(identifier, klass)
      if @klasses[identifier]
        raise DuplicateEntry, :registry => @name,
                              :identifiers => @klasses.keys
      else
        @klasses[identifier] = klass
      end
    end

    # Retrieve a class associated with the specified identifier
    #
    # @param identifier [Symbol]
    #
    # @return [Class]
    def retrieve(identifier)
      if (klass = @klasses[identifier])
        klass
      else
        raise UnknownEntry, :registry  => @name,
                            :identifier => identifier.inspect,
                            :identifiers => @klasses.keys
      end
    end

    # Generate a class instance with the given hash
    #
    # @param hash [Hash] The identifier and options for the new object
    # @option hash type [String] The identifier of the class to instantiate
    #
    # @return [Object] The generated object
    def generate(hash)
      config = hash.dup
      identifier = config.delete('type')

      klass = retrieve(identifier)

      klass.new_from_hash(hash)
    end

    def inspect
      "<#{self.class}: (#{@name}) keys: #{@klasses.keys.inspect}>"
    end
  end
end

Version data entries

1 entries across 1 versions & 1 rubygems

Version Path
vagrant-config_builder-0.2.0 lib/config_builder/class_registry.rb