Be careful with "memoize"

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 Over 12 years ago