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 web development

Do you need DevOps-experts?

Your development team has a full backlog? No time for infrastructure architecture? Our DevOps team is ready to support you!

  • We build reliable cloud solutions with Infrastructure as code
  • We are experts in security, Linux and databases
  • We support your dev team to perform
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)