Skip to content

Commit

Permalink
fix: default value set to true causes undefined method [] error (#108)
Browse files Browse the repository at this point in the history
  • Loading branch information
antoinesaliba authored Jul 5, 2024
1 parent 054d59f commit 6829bbf
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)
else
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 @@ -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})

Expand Down

0 comments on commit 6829bbf

Please sign in to comment.