Skip to content

Commit 2b6b210

Browse files
authored
Merge pull request #46 from belousovAV/fix-nil-coercion
Fix `nil` coercion for the case when `nil` used as default value instead of `Dry::Initializer::UNDEFINED`
2 parents 5b43831 + 128b484 commit 2b6b210

File tree

2 files changed

+31
-7
lines changed

2 files changed

+31
-7
lines changed

lib/dry/initializer/builders/attribute.rb

Lines changed: 6 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -20,7 +20,8 @@ def initialize(definition)
2020
@default = definition.default
2121
@source = definition.source
2222
@ivar = definition.ivar
23-
@null = definition.null ? "Dry::Initializer::UNDEFINED" : "nil"
23+
@default_null = "Dry::Initializer::UNDEFINED"
24+
@null = definition.null ? @default_null : "nil"
2425
@opts = "__dry_initializer_options__"
2526
@congif = "__dry_initializer_config__"
2627
@item = "__dry_initializer_definition__"
@@ -67,9 +68,11 @@ def coercion_line
6768
return unless @type
6869
arity = @type.is_a?(Proc) ? @type.arity : @type.method(:call).arity
6970
if arity.abs == 1
70-
"#{@val} = #{@item}.type.call(#{@val}) unless #{@null} == #{@val}"
71+
"#{@val} = #{@item}.type.call(#{@val})" \
72+
" unless #{@default_null} == #{@val}"
7173
else
72-
"#{@val} = #{@item}.type.call(#{@val}, self) unless #{@null} == #{@val}"
74+
"#{@val} = #{@item}.type.call(#{@val}, self)" \
75+
" unless #{@default_null} == #{@val}"
7376
end
7477
end
7578

spec/coercion_of_nil_spec.rb

Lines changed: 25 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -15,11 +15,32 @@ class Test::Baz
1515
let(:foo) { Test::Foo.new(nil) }
1616
let(:baz) { Test::Baz.new(nil) }
1717

18-
it "works with extend syntax" do
19-
expect(foo.bar).to eq 0
18+
context "default @null" do
19+
it "works with extend syntax" do
20+
expect(foo.bar).to eq 0
21+
end
22+
23+
it "works with include syntax" do
24+
expect(baz.qux).to eq 0
25+
end
2026
end
2127

22-
it "works with include syntax" do
23-
expect(baz.qux).to eq 0
28+
context "@null is nil" do
29+
before(:context) do
30+
@default_null = Dry::Initializer.instance_variable_get :@null
31+
Dry::Initializer.instance_variable_set :@null, nil
32+
end
33+
34+
after(:context) do
35+
Dry::Initializer.instance_variable_set :@null, @default_null
36+
end
37+
38+
it "works with extend syntax" do
39+
expect(foo.bar).to eq 0
40+
end
41+
42+
it "works with include syntax" do
43+
expect(baz.qux).to eq 0
44+
end
2445
end
2546
end

0 commit comments

Comments
 (0)