Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Alternative serialization for DataMapper objects in Rails

I'm working on on a caching layer in my Rails app and I'm having trouble caching original DataMapper objects. They seem to have a lot of stuff attached that make marshaling fail (I get an error about Marshal being unable to serialize a Proc object).

So I am considering writing my own pre-serialization and post-deserialization methods for caching. Specifically I will turn the DataMapper object into a list of tuples with this:

o = Foo.get(1234)
as_list = o.model.properties.map { |p| [p.name, o.send(p.name)] }

And then cache that list.

My question is: How do I reconstruct the DataMapper object in a way that allows me to use it as it if were constructed by a normal DataMapper query?

My naive approach of Foo.new(foo=bar, goo=baz) doesn't seem to connect it up with all of the foreign keys and stuff.

like image 882
guidoism Avatar asked Feb 23 '26 10:02

guidoism


1 Answers

After some "fun" code-spelunking I seem to have found something that works:

mc.set(key, HashWithIndifferentAccess[o.attributes])

as_hash = mc.get(key)
from_cache = Foo.load([as_hash], Foo.all.query).first

The load method on the model seems to be what get uses and the query seems to be required in order to get the repository names and a few other things.

like image 164
guidoism Avatar answered Feb 26 '26 03:02

guidoism



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!