Marshal after load callback

Hi!

ActiveRecord lazily defines attribute methods when .new or .allocate is
called. When Marshal loads object it doesn’t call any of this methods.
So if attribute methods were not defined before, restored object wont
have them.

I’ve tried to workaround the issue with marshal_load/marshal_dump
(_load/_dump) methods, but with no success. I don’t want to have a mess
with serialization, and super methods are not defined for this methods.

Here is the issue in rails repo with some more discussion.

Any ideas how this can be solved? Or maybe I should create feature
request for ruby?

Missed the link: AR: define_attribute_methods is not fired when record is loaded from marshal · Issue #18659 · rails/rails · GitHub

Not really. It’s for storing object which is being created in many
steps. It’s stored in cache between requests. So this data is not in DB
yet.

Max Melentiev wrote in post #1167235:

ActiveRecord lazily defines attribute methods when .new or .allocate is
called. When Marshal loads object it doesn’t call any of this methods.
So if attribute methods were not defined before, restored object wont
have them.

Any ideas how this can be solved? Or maybe I should create feature
request for ruby?

I am not sure it’s a good idea what you are trying to do there. With
marshaling you introduce a second persistence storage for the same
data. I do not think this is intended or even a good idea. Why do you
think you need this?

Max Melentiev wrote in post #1167252:

Not really. It’s for storing object which is being created in many
steps. It’s stored in cache between requests. So this data is not in DB
yet.

Hm, then maybe a builder pattern is more appropriate here. How does
your cache look like? Why do you need to marshal objects?

With a builder I would store steps for the builder and reproduce them on
each request. Anyway there should be serialization layer, which one i
think i can avoid with marshal. And I also use AR’s associations,
validations & typecasting. Cache is just a redis store.

Thanks for your reply! However the question was not about the
architecture but about the marshal hooks/tricks or maybe even kind of
feature request. Maybe I should post it to ruby-core forum.