memoist icon indicating copy to clipboard operation
memoist copied to clipboard

Memoize errors

Open njonsson opened this issue 11 years ago • 7 comments
trafficstars

I don’t know whether you’d consider this to be within the scope of Memoist, but I found a need for it.

As it stands, an error raised by a method prevents its memoization. This commit allows Memoist to cache not just successful results of a method but also errors. If a method is called with the same arguments, the same Exception object is raised without an additional call to the method.

njonsson avatar Jun 16 '14 17:06 njonsson

That's pretty cool. Not taking a stance on viability either way, but damn. That's cool.

pboling avatar Jun 16 '14 23:06 pboling

I would find this very useful

iainbeeston avatar Oct 21 '14 07:10 iainbeeston

For example, where the memoised function is expensive (eg network access, file IO or an expensive calculation)

iainbeeston avatar Oct 21 '14 08:10 iainbeeston

:+1: Bump. I really think this makes sense, after thinking about it for almost a year... :watch: If the goal of memoizable is to cache the result of a method call, this fixes a bug where it hasn't been doing that for exceptions.

@njonsson Based on this comment I think this may require a fork and a new project with expanded scope.

pboling avatar Mar 26 '15 21:03 pboling

Thanks for your contribution. And apologies I never looked at this before.

But...

Do you really think that's expected behaviour?

I guess it depends what you're trying to memoize. But if it's something that can fail, I'd like to believe you want to retry it somehow.

Eg.

class User < ActiveRecord::Base
  has_many :posts

  def post_titles
    posts.pluck(:title)
  end
  memoize :post_titles
end

If this fails, then the database connection is dead.

If the database connection is dead, then what do we do?

Presumably we have a retry scheme. Or maybe that happens at a lower level (eg deadlock retry)

So, I guess what I'm saying is "what's an example of an exception that we want to cache?"

I can only think of exceptions that we don't want to cache.

matthewrudy avatar Mar 27 '15 02:03 matthewrudy

But if it’s something that can fail, I’d like to believe you want to retry it somehow.

The API you established for memoized values applies to memoized errors, too. I’ve updated the MiniTest test to demonstrate that specifying the optional :reload argument calls the underlying method again.

njonsson avatar Apr 09 '15 16:04 njonsson

What about making it a configuration option?

  • Give a boolean saying that, for this particular memoization, you would like to cache errors

and/or

  • Give it an array which contains errors which you would like to memoize

cheerfulstoic avatar Mar 03 '16 13:03 cheerfulstoic