memoist
memoist copied to clipboard
Memoize errors
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.
That's pretty cool. Not taking a stance on viability either way, but damn. That's cool.
I would find this very useful
For example, where the memoised function is expensive (eg network access, file IO or an expensive calculation)
:+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.
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.
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.
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