From: Brian Buckley Date: 2005-11-04T05:25:14+09:00 Subject: memoize and yaml Hello, I am using the "memoize" module to eliminate having to redo complex, time-consuming calculations. It works great. However, when I yamlize my "memoized" object off to the database and then retrieve it back, all the memoizing is lost. My Ruby skills are still in development. In addition to normal yamlizing, how could one also yamlize the memoize information, so that yamlizing and back retains the methods that are to be memoized and also retains any prior saved (memoized) calculations? The test below on Foo illustrates what I am trying to do. Also below is the whole Memoize module. Any tips or pointers appreciated. Thanks! --Brian Buckley require 'test/unit' require 'yaml' require 'memoize' class TestMemoizeAndYaml < Test::Unit::TestCase class Foo include Memoize attr_reader :x, :y def initialize(x, y) @x, @y = x, y end def calc1(a, b) sleep 1 # fakes big, complex calc ans = calc2 + a + b end def calc2(c = 0) sleep 1 # another big, complex calc ans = x + y end end def exercise_foo(foo) 3.times{ foo.calc1 10,20 } end def test_memoize_and_yaml foo = Foo.new(1, 2) # first a foo without memoizing exercise_foo(foo) # without memoizing exercise_foo takes 6 seconds - good # now memoize it foo.memoize :calc1 # memoize calc1 foo.memoize :calc2 # and a 2nd method exercise_foo(foo) # good - now it takes only 2 secs because of the memoizing exercise_foo(foo) # and now no seconds because of the memoizing foo = YAML::load(foo.to_yaml) # to the database and back exercise_foo(foo) # but now exercise_foo is taking 6 secs again # how can I retain memoized state? # need to retain both the methods and the hashes of calculation histories end end #FYI... here is the Memoize module module Memoize MEMOIZE_VERSION = "1.1.0" def memoize(name) meth = method(name) cache = {} (class << self; self; end).class_eval do define_method(name) do |*args| cache.has_key?(args) ? cache[args] : cache[args] ||= meth.call(*args) end end cache end end