Sha256: 18e79a619b46ec9163ad28cdccfaa4f8d324d1c842b75827fcbb1052cf9ac82f

Contents?: true

Size: 897 Bytes

Versions: 2

Compression:

Stored size: 897 Bytes

Contents

require 'dry/types/decorator'

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

      # @return [Array]
      attr_reader :values

      # @return [Hash]
      attr_reader :mapping

      # @param [Definition] 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

2 entries across 2 versions & 1 rubygems

Version Path
dry-types-0.9.4 lib/dry/types/enum.rb
dry-types-0.9.3 lib/dry/types/enum.rb