Sha256: 8c9d4564eecf3ee9ce58a78e51037d395b9a179243ae1db41e3d4bca2aa9fb15

Contents?: true

Size: 910 Bytes

Versions: 3

Compression:

Stored size: 910 Bytes

Contents

require 'dry/types/decorator'

module Dry
  module Types
    class Enum
      include Type
      include Dry::Equalizer(:type, :options, :values)
      include Decorator

      # @return [Array]
      attr_reader :values

      # @return [Hash]
      attr_reader :mapping

      # @param [Type] type
      # @param [Hash] options
      # @option options [Array] :values
      def initialize(type, options)
        super
        @values = options.fetch(:values).freeze
        @values.each(&:freeze)
        @mapping = values.each_with_object({}) { |v, h| h[values.index(v)] = v }.freeze
      end

      # @param [Object] input
      # @return [Object]
      def call(input)
        value =
          if values.include?(input)
            input
          elsif mapping.key?(input)
            mapping[input]
          end

        type[value || input]
      end
      alias_method :[], :call
    end
  end
end

Version data entries

3 entries across 3 versions & 1 rubygems

Version Path
dry-types-0.10.2 lib/dry/types/enum.rb
dry-types-0.10.1 lib/dry/types/enum.rb
dry-types-0.10.0 lib/dry/types/enum.rb