-
-
Notifications
You must be signed in to change notification settings - Fork 46
/
attribute.rb
81 lines (70 loc) · 2.1 KB
/
attribute.rb
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
module Dry::Initializer::Builders
# @private
class Attribute
def self.[](definition)
new(definition).call
end
def call
lines.compact
end
private
# rubocop: disable Metrics/MethodLength
def initialize(definition)
@definition = definition
@option = definition.option
@type = definition.type
@optional = definition.optional
@default = definition.default
@source = definition.source
@ivar = definition.ivar
@null = definition.null ? "Dry::Initializer::UNDEFINED" : "nil"
@opts = "__dry_initializer_options__"
@congif = "__dry_initializer_config__"
@item = "__dry_initializer_definition__"
@val = @option ? "__dry_initializer_value__" : @source
end
# rubocop: enable Metrics/MethodLength
def lines
[
"",
definition_line,
reader_line,
default_line,
coercion_line,
assignment_line
]
end
def reader_line
return unless @option
@optional ? optional_reader : required_reader
end
def optional_reader
"#{@val} = #{@opts}.fetch(:'#{@source}', #{@null})"
end
def required_reader
"#{@val} = #{@opts}.fetch(:'#{@source}')" \
" { raise KeyError, \"\#{self.class}: #{@definition} is required\" }"
end
def definition_line
return unless @type || @default
"#{@item} = __dry_initializer_config__.definitions[:'#{@source}']"
end
def default_line
return unless @default
"#{@val} = instance_exec(&#{@item}.default) if #{@val} == #{@null}"
end
def coercion_line
return unless @type
arity = @type.is_a?(Proc) ? @type.arity : @type.method(:call).arity
if arity.abs == 1
"#{@val} = #{@item}.type.call(#{@val}) unless #{@val} == #{@null}"
else
"#{@val} = #{@item}.type.call(#{@val}, self) unless #{@val} == #{@null}"
end
end
def assignment_line
"#{@ivar} = #{@val}" \
" unless #{@val} == #{@null} && instance_variable_defined?(:#{@ivar})"
end
end
end