0
0
Ruby on Railsframework~5 mins

Low-level caching with Rails.cache

Choose your learning style9 modes available
Introduction

Low-level caching helps your Rails app remember data so it doesn't have to do the same work again. This makes your app faster and saves resources.

You want to store the result of a slow database query to reuse it later.
You want to cache the output of a complex calculation to avoid repeating it.
You want to keep data in memory for a short time to speed up repeated requests.
You want to cache external API responses to reduce calls and improve speed.
Syntax
Ruby on Rails
Rails.cache.fetch(key, options = {}) do
  # code to get data if cache is empty
end
The key is a unique name for the cached data.
The block runs only if the cache for the key is empty or expired.
Examples
This caches the user with ID 1. If cached, it returns the user from cache; otherwise, it fetches from the database.
Ruby on Rails
Rails.cache.fetch('user_1') { User.find(1) }
This caches the current time for 5 minutes. After that, it refreshes the cache.
Ruby on Rails
Rails.cache.fetch('time', expires_in: 5.minutes) { Time.now }
You can write and read cache manually without a block.
Ruby on Rails
Rails.cache.write('greeting', 'Hello!')
Rails.cache.read('greeting') # returns 'Hello!'
Sample Program

This controller action caches all products for 10 minutes. It avoids hitting the database on every request, speeding up the page load.

Ruby on Rails
class ProductsController < ApplicationController
  def index
    @products = Rails.cache.fetch('all_products', expires_in: 10.minutes) do
      Product.all.to_a
    end
  end
end
OutputSuccess
Important Notes

Always use unique keys to avoid cache conflicts.

Set expiration times to keep cache fresh and avoid stale data.

Use Rails.cache.delete(key) to remove cache when data changes.

Summary

Low-level caching stores data with a unique key to speed up repeated access.

Use Rails.cache.fetch with a block to cache data easily.

Remember to manage cache expiration and invalidation for fresh data.