Class: Dry::Types::Enum

Inherits:
Object
  • Object
show all
Includes:
Decorator
Defined in:
lib/dry/types/enum.rb

Instance Attribute Summary collapse

Attributes included from Decorator

#type

Attributes included from Options

#options

Instance Method Summary collapse

Methods included from Decorator

#constrained?, #constructor, #default?, #respond_to_missing?, #try, #valid?

Methods included from Options

#meta, #with

Constructor Details

#initialize(type, options) ⇒ Enum

Returns a new instance of Enum.



11
12
13
14
15
16
# File 'lib/dry/types/enum.rb', line 11

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

Dynamic Method Handling

This class handles dynamic methods through the method_missing method in the class Dry::Types::Decorator

Instance Attribute Details

#mappingObject (readonly)

Returns the value of attribute mapping.



9
10
11
# File 'lib/dry/types/enum.rb', line 9

def mapping
  @mapping
end

#valuesObject (readonly)

Returns the value of attribute values.



9
10
11
# File 'lib/dry/types/enum.rb', line 9

def values
  @values
end

Instance Method Details

#call(input) ⇒ Object Also known as: []



18
19
20
21
22
23
24
25
26
27
# File 'lib/dry/types/enum.rb', line 18

def call(input)
  value =
    if values.include?(input)
      input
    elsif mapping.key?(input)
      mapping[input]
    end

  type[value || input]
end