guidoism
guidoism

Reputation: 8158

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.

Upvotes: 3

Views: 753

Answers (1)

guidoism
guidoism

Reputation: 8158

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.

Upvotes: 1

Related Questions