Sha256: 67ce9bf7a8816e226684d4d632f7ba82035ab628ff093250165b438cdabf8582

Contents?: true

Size: 1.38 KB

Versions: 8

Compression:

Stored size: 1.38 KB

Contents

# encoding: utf-8

module TTY
  class Prompt
    # Immutable collection of converters for type transformation
    #
    # @api private
    class ConverterRegistry
      # Create a registry of conversions
      #
      # @param [Hash] registry
      #
      # @api private
      def initialize(registry = {})
        @_registry = registry.dup.freeze
        freeze
      end

      # Register converter
      #
      # @param [Symbol] name
      #   the converter name
      #
      # @api public
      def register(name, contents = nil, &block)
        item = block_given? ? block : contents

        if key?(name)
          raise ArgumentError,
                "Converter for #{name.inspect} already registered"
        end
        self.class.new(@_registry.merge(name => item))
      end

      # Check if converter is registered
      #
      # @return [Boolean]
      #
      # @api public
      def key?(key)
        @_registry.key?(key)
      end

      # Execute converter
      #
      # @api public
      def call(name, input)
        if name.respond_to?(:call)
          converter = name
        else
          converter = @_registry.fetch(name) do
            raise ArgumentError, "#{name.inspect} is not registered"
          end
        end
        converter[input]
      end
      alias [] call

      def inspect
        @_registry.inspect
      end
    end # ConverterRegistry
  end # Prompt
end # TTY

Version data entries

8 entries across 8 versions & 2 rubygems

Version Path
tty-prompt-0.15.0 lib/tty/prompt/converter_registry.rb
tty-prompt-0.14.0 lib/tty/prompt/converter_registry.rb
tty-prompt-0.13.2 lib/tty/prompt/converter_registry.rb
tty-prompt-0.13.1 lib/tty/prompt/converter_registry.rb
tty-prompt-0.13.0 lib/tty/prompt/converter_registry.rb
austb-tty-prompt-0.13.0 lib/tty/prompt/converter_registry.rb
tty-prompt-0.12.0 lib/tty/prompt/converter_registry.rb
tty-prompt-0.11.0 lib/tty/prompt/converter_registry.rb