active_type icon indicating copy to clipboard operation
active_type copied to clipboard

Support for `read_attribute_before_type_cast`

Open kalsan opened this issue 1 year ago • 1 comments

Hi! Hope you're doing well.

Using active_type with custom serialization breaks because calling read_attribute_before_type_cast on a ActiveType::Object returns nil. I've managed to work around the problem by implementing the following in the custom serializer:

raw_data = defined?(ActiveType::Object) && is_a?(ActiveType::Object) ? virtual_attributes[attribute_name.to_s] : read_attribute_before_type_cast(attribute_name)
result = my_custom_type_value.deserialize(raw_data)

I thus suspect that overriding read_attribute_before_type_cast in active_type and having it return virtual_attributes[attribute_name] would likely fix this. However, I'm not sure about compatibility with different Rails versions.

What do you think, would this be a sensible way to fix this problem?

Best, Kalsan

kalsan avatar Dec 30 '24 09:12 kalsan

Hi @kalsan. Sorry for the late response. Unfortunately, issues of this kind recently keep appearing. Your suspicion that this is potentially difficult to keep aligned across Rails versions, since ActiveRecord (understandably) keeps adding different mechanisms to access attributes. I feel we will have to find a different mechanism for the whole "virtual attributes" thing at some point.

For now,

  • I might find time to attempt a fix, but cannot currently make promises
  • I would most likely merge a PR if someone attempts to fix this, unless it becomes unreasonably complex. I suspect defining read_attribute_before_type_case could work.

kratob avatar Jan 17 '25 16:01 kratob