Sha256: 21b4999dd1779c1a496578581844744d2ce896494531832d1338454430ea4c10

Contents?: true

Size: 674 Bytes

Versions: 5

Compression:

Stored size: 674 Bytes

Contents

require 'dry/types/decorator'

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

      attr_reader :values, :mapping

      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

      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

5 entries across 5 versions & 1 rubygems

Version Path
dry-types-0.9.2 lib/dry/types/enum.rb
dry-types-0.9.1 lib/dry/types/enum.rb
dry-types-0.9.0 lib/dry/types/enum.rb
dry-types-0.8.1 lib/dry/types/enum.rb
dry-types-0.8.0 lib/dry/types/enum.rb