File: converter_registry.rb

package info (click to toggle)
ruby-tty-prompt 0.23.1-1
  • links: PTS, VCS
  • area: main
  • in suites: bookworm, forky, sid, trixie
  • size: 1,452 kB
  • sloc: ruby: 8,847; makefile: 4
file content (69 lines) | stat: -rw-r--r-- 1,538 bytes parent folder | download
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
# frozen_string_literal: true

require "forwardable"

module TTY
  class Prompt
    # Immutable collection of converters for type transformation
    #
    # @api private
    class ConverterRegistry
      extend Forwardable

      def_delegators "@__registry", :keys

      # Create a registry of conversions
      #
      # @param [Hash] registry
      #
      # @api private
      def initialize(registry = {})
        @__registry = registry.dup
      end

      # Check if conversion is available
      #
      # @param [String] name
      #
      # @return [Boolean]
      #
      # @api public
      def contain?(name)
        conv_name = name.to_s.downcase.to_sym
        @__registry.key?(conv_name)
      end

      # Register a conversion
      #
      # @param [Symbol] name
      #   the converter name
      #
      # @api public
      def register(*names, &block)
        names.each do |name|
          if contain?(name)
            raise ConversionAlreadyDefined,
                  "converter for #{name.inspect} is already registered"
          end
          @__registry[name] = block
        end
      end

      # Execute converter
      #
      # @api public
      def [](name)
        conv_name = name.to_s.downcase.to_sym
        @__registry.fetch(conv_name) do
          raise UnsupportedConversion,
                "converter #{conv_name.inspect} is not registered"
        end
      end
      alias fetch []

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