Be careful with "memoize"

Posted Over 12 years ago. Visible to the public.

ActiveSupport's memoize has a dangerous feature you might not know about.

Assume you have

class DeepThought
  extend ActiveSupport::Memoizable

  def life_universe_and_everything
     # some lengthy calculation returning 42
  end
  memoize :life_universe_and_everything
end

Then #life_universe_and_everything will of course cache the result after calculating it once. However, you can trigger a recalculation by calling #life_universe_and_everything(true).

If, however, your method looks like

def life_universe(and_everything = false)
  ...
end
memoize :life_universe

a call to #life_universe(true) will actually trigger a reload and not pass the parameter at all.

To clarify: This not only disables the memoization, but will also return wrong results!

The best solution is to use the Memoizer gem instead.

Tobias Kraze
Last edit
Almost 12 years ago
License
Source code in this card is licensed under the MIT License.
Posted by Tobias Kraze to makandra dev (2011-11-07 15:10)