From 6829bbf8b6bf47db51209e9874608b7e10c38b8e Mon Sep 17 00:00:00 2001 From: Antoine Saliba Date: Thu, 4 Jul 2024 22:36:58 -0400 Subject: [PATCH] fix: default value set to true causes undefined method [] error (#108) --- lib/typed/serializer.rb | 4 ++-- test/typed/hash_serializer_test.rb | 28 ++++++++++++++++++++++++++++ 2 files changed, 30 insertions(+), 2 deletions(-) diff --git a/lib/typed/serializer.rb b/lib/typed/serializer.rb index b07263e..6fd7729 100644 --- a/lib/typed/serializer.rb +++ b/lib/typed/serializer.rb @@ -35,8 +35,8 @@ def deserialize_from_creation_params(creation_params) results = schema.fields.map do |field| value = creation_params.fetch(field.name, nil) - if value.nil? && field.default - Success.new(Validations::ValidatedValue.new(field.default)) + if value.nil? && !field.default.nil? + Success.new(Validations::ValidatedValue.new(name: field.name, value: field.default)) elsif value.nil? || field.works_with?(value) field.validate(value) else diff --git a/test/typed/hash_serializer_test.rb b/test/typed/hash_serializer_test.rb index 4813ef7..2178738 100644 --- a/test/typed/hash_serializer_test.rb +++ b/test/typed/hash_serializer_test.rb @@ -1,6 +1,18 @@ # typed: true class HashSerializerTest < Minitest::Test + class StructWithBooleanDefaultSetToTrue < T::Struct + include ActsAsComparable + + const :tired, T::Boolean, default: true + end + + class StructWithBooleanDefaultSetToFalse < T::Struct + include ActsAsComparable + + const :tired, T::Boolean, default: false + end + def setup @serializer = Typed::HashSerializer.new(schema: Typed::Schema.from_struct(Person)) end @@ -109,6 +121,22 @@ def test_it_can_deserialize_with_nested_object assert_payload(ALEX_PERSON, result) end + def test_it_can_deserialize_with_default_value_boolean_true + serializer = Typed::HashSerializer.new(schema: Typed::Schema.from_struct(StructWithBooleanDefaultSetToTrue)) + result = serializer.deserialize({}) + + assert_success(result) + assert_payload(StructWithBooleanDefaultSetToTrue.new(tired: true), result) + end + + def test_it_can_deserialize_with_default_value_boolean_false + serializer = Typed::HashSerializer.new(schema: Typed::Schema.from_struct(StructWithBooleanDefaultSetToFalse)) + result = serializer.deserialize({}) + + assert_success(result) + assert_payload(StructWithBooleanDefaultSetToFalse.new(tired: false), result) + end + def test_it_reports_validation_errors_on_deserialize result = @serializer.deserialize({name: "Max", ruby_rank: RubyRank::Luminary})