Skip to content

Commit

Permalink
Merge branch 'main' into antoine.dealing_with_multiple_types
Browse files Browse the repository at this point in the history
  • Loading branch information
maxveldink authored Jul 5, 2024
2 parents b792283 + 6829bbf commit 331d8eb
Show file tree
Hide file tree
Showing 2 changed files with 30 additions and 2 deletions.
4 changes: 2 additions & 2 deletions lib/typed/serializer.rb
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down
28 changes: 28 additions & 0 deletions test/typed/hash_serializer_test.rb
Original file line number Diff line number Diff line change
@@ -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
Expand Down Expand Up @@ -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})
Expand Down

0 comments on commit 331d8eb

Please sign in to comment.