-
-
Notifications
You must be signed in to change notification settings - Fork 42
Expand file tree
/
Copy pathattribute.rb
More file actions
69 lines (57 loc) · 1.66 KB
/
attribute.rb
File metadata and controls
69 lines (57 loc) · 1.66 KB
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
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'
@congif = '__dry_initializer_config__'
@item = '__dry_initializer_definition__'
@val = @source
end
# rubocop: enable Metrics/MethodLength
def lines
[
'',
definition_line,
default_line,
coercion_line,
assignment_line
]
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 #{@null} == #{@val}"
end
def coercion_line
return unless @type
arity = @type.is_a?(Proc) ? @type.arity : @type.method(:call).arity
if arity.equal?(1) || arity.negative?
"#{@val} = #{@item}.type.call(#{@val}) unless #{@null} == #{@val}"
else
"#{@val} = #{@item}.type.call(#{@val}, self) unless #{@null} == #{@val}"
end
end
def assignment_line
"#{@ivar} = #{@val}" \
" unless #{@null} == #{@val} && instance_variable_defined?(:#{@ivar})"
end
end
end