Sha256: 0a9cb95edac32a5132744a3538b7f5ec7b1c3fa1181ce771cbb0ac20c516d5bd

Contents?: true

Size: 1014 Bytes

Versions: 22

Compression:

Stored size: 1014 Bytes

Contents

module R10K

  # This implements a factory by storing classes indexed with a given key and
  # creates objects based on that key.
  class KeyedFactory

    # @!attribute [r] implementations
    #   @return [Hash<Object, Class>] A hash of keys and the associated
    #     implementations that this factory can generate.
    attr_reader :implementations

    def initialize
      @implementations = {}
    end

    def register(key, klass)
      if @implementations.has_key?(key)
        raise DuplicateImplementationError, "Class already registered for #{key}"
      else
        @implementations[key] = klass
      end
    end

    def retrieve(key)
      @implementations[key]
    end

    def generate(key, *args)
      if (impl = @implementations[key])
        impl.new(*args)
      else
        raise UnknownImplementationError, "No class registered for #{key}"
      end
    end

    class DuplicateImplementationError < StandardError; end
    class UnknownImplementationError < StandardError; end
  end
end

Version data entries

22 entries across 22 versions & 1 rubygems

Version Path
r10k-2.3.1 lib/r10k/keyed_factory.rb
r10k-2.3.0 lib/r10k/keyed_factory.rb
r10k-2.2.2 lib/r10k/keyed_factory.rb
r10k-2.2.1 lib/r10k/keyed_factory.rb
r10k-2.2.0 lib/r10k/keyed_factory.rb
r10k-2.1.1 lib/r10k/keyed_factory.rb
r10k-2.1.0 lib/r10k/keyed_factory.rb
r10k-2.0.3 lib/r10k/keyed_factory.rb
r10k-2.0.2 lib/r10k/keyed_factory.rb
r10k-2.0.1 lib/r10k/keyed_factory.rb
r10k-2.0.0 lib/r10k/keyed_factory.rb
r10k-1.5.1 lib/r10k/keyed_factory.rb
r10k-1.4.2 lib/r10k/keyed_factory.rb
r10k-1.4.1 lib/r10k/keyed_factory.rb
r10k-1.4.0 lib/r10k/keyed_factory.rb
r10k-1.3.5 lib/r10k/keyed_factory.rb
r10k-1.3.4 lib/r10k/keyed_factory.rb
r10k-1.3.3 lib/r10k/keyed_factory.rb
r10k-1.3.2 lib/r10k/keyed_factory.rb
r10k-1.3.1 lib/r10k/keyed_factory.rb