class Dry::Types::Enum

Enum types can be used to define an enum on top of an existing type

@api public

Attributes

inverted_mapping[R]

@return [Hash]

mapping[R]

@return [Hash]

values[R]

@return [Array]

Public Class Methods

new(type, **options) click to toggle source

@param [Type] type @param [Hash] options @option options [Array] :values

@api private

Calls superclass method Dry::Types::Decorator::new
# File lib/dry/types/enum.rb, line 31
def initialize(type, **options)
  super
  @mapping = options.fetch(:mapping).freeze
  @values = @mapping.keys.freeze
  @inverted_mapping = @mapping.invert.freeze
  freeze
end

Public Instance Methods

call_safe(input, &block) click to toggle source

@return [Object]

@api private

# File lib/dry/types/enum.rb, line 49
def call_safe(input, &block)
  type.call_safe(map_value(input), &block)
end
call_unsafe(input) click to toggle source

@return [Object]

@api private

# File lib/dry/types/enum.rb, line 42
def call_unsafe(input)
  type.call_unsafe(map_value(input))
end
default(*) click to toggle source

@api private

# File lib/dry/types/enum.rb, line 61
def default(*)
  raise ".enum(*values).default(value) is not supported. Call "\
        ".default(value).enum(*values) instead"
end
inspect()
Alias for: to_s
to_ast(meta: true) click to toggle source

@see Nominal#to_ast

@api public

# File lib/dry/types/enum.rb, line 72
def to_ast(meta: true)
  [:enum, [type.to_ast(meta: meta), mapping]]
end
to_s() click to toggle source

@return [String]

@api public

# File lib/dry/types/enum.rb, line 79
def to_s
  PRINTER.(self)
end
Also aliased as: inspect
try(input) click to toggle source

@see Dry::Types::Constrained#try

@api public

Calls superclass method Dry::Types::Decorator#try
# File lib/dry/types/enum.rb, line 56
def try(input)
  super(map_value(input))
end

Private Instance Methods

map_value(input) click to toggle source

Maps a value

@param [Object] input

@return [Object]

@api private

# File lib/dry/types/enum.rb, line 93
def map_value(input)
  if input.equal?(Undefined)
    type.call
  elsif mapping.key?(input)
    input
  else
    inverted_mapping.fetch(input, input)
  end
end