diff --git a/lib/typed/serializer.rb b/lib/typed/serializer.rb index c44f3bf..b795317 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) elsif field.type.class <= T::Types::Union diff --git a/test/typed/hash_serializer_test.rb b/test/typed/hash_serializer_test.rb index 58cdd65..d8145d8 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 @@ -129,6 +141,22 @@ def test_if_it_cannot_be_deserialized_against_something_with_multiple_types_it_w assert_failure(result) assert_error(Typed::Validations::ValidationError.new('Enum RubyRank key not found: "not valid", Enum DiamondRank key not found: "not valid"'), 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", stone_rank: RubyRank::Luminary})