From b6b98f2ff6756218039eabfe100b6b409c0b4017 Mon Sep 17 00:00:00 2001 From: Logan Glickfield Date: Mon, 25 Sep 2023 13:06:55 -0400 Subject: [PATCH] Allow default value for String/Numeric Sets to be unset The fix in #112 had the side effect of calling `type_cast` on `nil` if the `default_value` was unset. Because the `StringSetMarshaler` and `NumericSetMarshaler` both convert `nil` to `Set.new`, this caused the unset default value in practice to become `Set.new` instead of `nil`. Ultimately this caused downstream effects such as always persisting empty or unset sets as `nil` despite the `#persist_nil?` returning `false`. --- lib/aws-record/record/attribute.rb | 8 ++++++-- spec/aws-record/record/attribute_spec.rb | 12 ++++++++++++ 2 files changed, 18 insertions(+), 2 deletions(-) diff --git a/lib/aws-record/record/attribute.rb b/lib/aws-record/record/attribute.rb index 6f9f88e5..a9c66f3e 100644 --- a/lib/aws-record/record/attribute.rb +++ b/lib/aws-record/record/attribute.rb @@ -40,8 +40,12 @@ def initialize(name, options = {}) @dynamodb_type = options[:dynamodb_type] @marshaler = options[:marshaler] || DefaultMarshaler @persist_nil = options[:persist_nil] - dv = options[:default_value] - @default_value_or_lambda = _is_lambda?(dv) ? dv : type_cast(dv) + @default_value_or_lambda = if options.key?(:default_value) + dv = options[:default_value] + _is_lambda?(dv) ? dv : type_cast(dv) + else + nil + end end # Attempts to type cast a raw value into the attribute's type. This call diff --git a/spec/aws-record/record/attribute_spec.rb b/spec/aws-record/record/attribute_spec.rb index 3a5458d7..4db14b87 100644 --- a/spec/aws-record/record/attribute_spec.rb +++ b/spec/aws-record/record/attribute_spec.rb @@ -50,6 +50,18 @@ module Record expect(a.default_value).to eq({}) end + + it 'does not type_cast unset value' do + m = Marshalers::StringSetMarshaler.new + a = Attribute.new(:foo, marshaler: m) + expect(a.default_value).to be_nil + end + + it 'type casts nil value' do + m = Marshalers::StringSetMarshaler.new + a = Attribute.new(:foo, marshaler: m, default_value: nil) + expect(a.default_value).to be_a(Set) + end end end end