You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
By default, every call to a cached method hits the cache adapter, which includes deserialization. For methods where the deserialized object is expensive to reconstruct (e.g., large ActiveRecord collections), you can enable per-instance memoization so that repeated calls on the **same object** skip the adapter entirely:
260
+
261
+
```ruby
262
+
# From examples/memoize_example.rb
263
+
264
+
classExpensiveService
265
+
includeCacheable
266
+
267
+
cacheable :without_memoize
268
+
269
+
cacheable :with_memoize, memoize:true
270
+
271
+
defwithout_memoize
272
+
puts' [method] computing value'
273
+
42
274
+
end
275
+
276
+
defwith_memoize
277
+
puts' [method] computing value'
278
+
42
279
+
end
280
+
end
281
+
```
282
+
283
+
Using a logging adapter wrapper (see `examples/memoize_example.rb` for the full setup), the difference becomes clear:
[cache] fetch ["ExpensiveService", :without_memoize] <-- adapter hit again (deserialization cost)
290
+
291
+
--- with memoize: true ---
292
+
[cache] fetch ["ExpensiveService", :with_memoize]
293
+
[method] computing value
294
+
<-- no adapter hit on second call
295
+
296
+
--- after clearing ---
297
+
[cache] fetch ["ExpensiveService", :with_memoize] <-- adapter hit again after clear
298
+
[method] computing value
299
+
```
300
+
301
+
**Important**: Memoized values persist for the lifetime of the object instance, and after the first call they bypass the cache adapter entirely. This means adapter-driven expiration (`expires_in`) and other backend invalidation mechanisms will **not** be re-checked while the instance stays alive. If your cache key changes (e.g., `cache_key` based on `updated_at`), the memoized value will also **not** automatically update. This is especially important for class-method memoization (where the "instance" is the class itself), because the memo can effectively outlive the cache TTL. Use `memoize: true` only when you know the value will not change for the lifetime of the instance (or class), or call `clear_#{method}_cache` explicitly when needed.
302
+
257
303
### Per-Class Cache Adapter
258
304
259
305
By default, all classes use the global adapter set via `Cacheable.cache_adapter`. If you need a specific class to use a different cache backend, you can set one directly on the class:
adapter.fetch(__send__(method_names[:key_format_method_name], *args, **kwargs),opts[:cache_options])do# rubocop:disable Lint/UselessDefaultValueArgument -- not Hash#fetch; second arg is cache options (e.g. expires_in) passed to the adapter
51
+
result=adapter.fetch(cache_key,opts[:cache_options])do# rubocop:disable Lint/UselessDefaultValueArgument -- not Hash#fetch; second arg is cache options (e.g. expires_in) passed to the adapter
0 commit comments