Read more

Be careful with "memoize"

Tobias Kraze
November 07, 2011Software engineer at makandra GmbH

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

Illustration online protection

Rails Long Term Support

Rails LTS provides security patches for old versions of Ruby on Rails (2.3, 3.2, 4.2 and 5.2)

  • Prevents you from data breaches and liability risks
  • Upgrade at your own pace
  • Works with modern Rubies
Read more Show archive.org snapshot

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.

Posted by Tobias Kraze to makandra dev (2011-11-07 16:10)