Serializing and deserializing a Cookie Jar

less than 1 minute read

I was recently working on a way to serialize and deserialize a Faraday connection that uses HTTP::CookieJar to manage persistent cookies across requests.

I needed to do this because I wanted a way to “freeze” an HTTP connection instance, and later “thaw” it to resume the operation — without consuming a ton of space in memory.

However, when I tried serializing it using good ole’ Marshal.dump(cookie_jar), it failed:

Traceback (most recent call last):
        2: from (irb):62
        1: from (irb):62:in `dump'
TypeError (no _dump_data is defined for class Thread::Mutex)

Solution: Accessing instance variables directly

The solution was pretty simple, albeit rather hacky. You can access the store directly by using:

cookie_hash = cookie_jar.store.instance_variable_get(:@jar)
serialized_cookie_jar_str = Marshal.dump(cookie_hash)

To restore it, you can do a set like so:

cookie_jar = Marshal.load(serialized_cookie_jar_str)
cookie_jar.store.instance_variable_set(:@jar, cookie_jar)

Hope this helps someone!