byroot / activerecord-typedstore

ActiveRecord::Store but with type definition
MIT License
437 stars 57 forks source link

Fix array set to [] when value is nil and default is provided #103

Closed TayKangSheng closed 11 months ago

TayKangSheng commented 11 months ago

Bug issue: https://github.com/byroot/activerecord-typedstore/issues/80

Took a stab at this bug because I was hoping to use this feature. Added comments in the code to try to explain what is wrong and what are my recommendations.

I have identified 2 problems that caused this to happen.

  1. When #extract_default happens, #type_cast wrongly cast the default value to the stringified version of the array because @array was not set yet and the default value is not nil.
  2. During the cast of the actual value (which is nil), @array is set but value is a String. [] is then returned.

Recommendations

  1. Assign @array before extracting the default value. This allows the default to be casted properly.
  2. If 1) the option array: true is set, 2) a default is provided and 3) value is nil; always default to the provided default.

Happy to hear any feedbacks and take any recommendations.

byroot commented 11 months ago

Merged a bit modified as https://github.com/byroot/activerecord-typedstore/pull/104