Class: Dry::Types::Enum
Instance Attribute Summary collapse
Attributes included from Decorator
#type
Attributes included from Options
#options
Instance Method Summary
collapse
Methods included from Decorator
#constrained?, #decorate?, #default?, #method_missing, #respond_to_missing?, #try, #valid?
Methods included from Options
#meta, #pristine, #with
Constructor Details
#initialize(type, options) ⇒ Enum
Returns a new instance of Enum.
19
20
21
22
23
24
|
# File 'lib/dry/types/enum.rb', line 19
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
#mapping ⇒ Hash
14
15
16
|
# File 'lib/dry/types/enum.rb', line 14
def mapping
@mapping
end
|
11
12
13
|
# File 'lib/dry/types/enum.rb', line 11
def values
@values
end
|
Instance Method Details
#call(input) ⇒ Object
Also known as:
[]
28
29
30
31
32
33
34
35
36
37
|
# File 'lib/dry/types/enum.rb', line 28
def call(input)
value =
if values.include?(input)
input
elsif mapping.key?(input)
mapping[input]
end
type[value || input]
end
|
#default ⇒ Object
40
41
42
43
|
# File 'lib/dry/types/enum.rb', line 40
def default(*)
raise '.enum(*values).default(value) is not supported. Call '\
'.default(value).enum(*values) instead'
end
|
#to_ast(meta: true) ⇒ Object
48
49
50
|
# File 'lib/dry/types/enum.rb', line 48
def to_ast(meta: true)
[:enum, [type.to_ast(meta: meta), meta ? self.meta : EMPTY_HASH]]
end
|