Basic Caching
Use thecache method to cache a block of content. Phlex automatically generates a cache key based on your class, method, and line number:
How Cache Keys Work
Phlex automatically generates cache keys that include:- App version key - Invalidates cache when deploying new code
- Class name - Prevents collisions between different classes
- Object ID (in development with reloading enabled)
- Method name - Prevents collisions between different methods
- Line number - Prevents collisions between different cache calls
- Custom keys - Your provided cache keys (like the product object)
Low-Level Caching
For full control over the cache key, uselow_level_cache. This is useful when you want complete responsibility for cache invalidation:
Unlike
cache, the low_level_cache method requires you to pass an array as the cache key. This gives you complete control but also full responsibility for cache invalidation.Setting Up a Cache Store
To use caching, you need to implement thecache_store method in your component:
Using Phlex’s FIFOCacheStore
Phlex includes a fast in-memory FIFO cache store:Caching with Fragments
Caching works seamlessly with fragment rendering for selective updates:Cache Reloading in Development
Enable cache reloading during development to automatically invalidate cache when code changes:Custom App Version Key
Override theapp_version_key method to customize cache invalidation on deployment:
Performance Considerations
Choose the right cache store
For development, use
FIFOCacheStore. In production, consider Redis or Memcached through Rails cache.Cache at the right level
Cache expensive operations like database queries or markdown rendering, not simple HTML.
Use cache keys effectively
Pass objects that respond to
cache_key_with_version or cache_key for automatic cache invalidation.