Sha256: 141eee8b2bb9a803f7561619a2529be165ffba48d7f69014b900978349becf50

Contents?: true

Size: 619 Bytes

Versions: 4

Compression:

Stored size: 619 Bytes

Contents

require 'dry/types/decorator'

module Dry
  module Types
    class Enum
      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

4 entries across 4 versions & 1 rubygems

Version Path
dry-types-0.7.2 lib/dry/types/enum.rb
dry-types-0.7.1 lib/dry/types/enum.rb
dry-types-0.7.0 lib/dry/types/enum.rb
dry-types-0.6.0 lib/dry/types/enum.rb