Skip to content

Commit

Permalink
Fix nil coercion
Browse files Browse the repository at this point in the history
  • Loading branch information
belousovAV committed Sep 9, 2018
1 parent 5b43831 commit 128b484
Show file tree
Hide file tree
Showing 2 changed files with 31 additions and 7 deletions.
9 changes: 6 additions & 3 deletions lib/dry/initializer/builders/attribute.rb
Original file line number Diff line number Diff line change
Expand Up @@ -20,7 +20,8 @@ def initialize(definition)
@default = definition.default
@source = definition.source
@ivar = definition.ivar
@null = definition.null ? "Dry::Initializer::UNDEFINED" : "nil"
@default_null = "Dry::Initializer::UNDEFINED"
@null = definition.null ? @default_null : "nil"
@opts = "__dry_initializer_options__"
@congif = "__dry_initializer_config__"
@item = "__dry_initializer_definition__"
Expand Down Expand Up @@ -67,9 +68,11 @@ 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 #{@null} == #{@val}"
"#{@val} = #{@item}.type.call(#{@val})" \
" unless #{@default_null} == #{@val}"
else
"#{@val} = #{@item}.type.call(#{@val}, self) unless #{@null} == #{@val}"
"#{@val} = #{@item}.type.call(#{@val}, self)" \
" unless #{@default_null} == #{@val}"
end
end

Expand Down
29 changes: 25 additions & 4 deletions spec/coercion_of_nil_spec.rb
Original file line number Diff line number Diff line change
Expand Up @@ -15,11 +15,32 @@ class Test::Baz
let(:foo) { Test::Foo.new(nil) }
let(:baz) { Test::Baz.new(nil) }

it "works with extend syntax" do
expect(foo.bar).to eq 0
context "default @null" do
it "works with extend syntax" do
expect(foo.bar).to eq 0
end

it "works with include syntax" do
expect(baz.qux).to eq 0
end
end

it "works with include syntax" do
expect(baz.qux).to eq 0
context "@null is nil" do
before(:context) do
@default_null = Dry::Initializer.instance_variable_get :@null
Dry::Initializer.instance_variable_set :@null, nil
end

after(:context) do
Dry::Initializer.instance_variable_set :@null, @default_null
end

it "works with extend syntax" do
expect(foo.bar).to eq 0
end

it "works with include syntax" do
expect(baz.qux).to eq 0
end
end
end

0 comments on commit 128b484

Please sign in to comment.