0
0
Ruby on Railsframework~30 mins

Low-level caching with Rails.cache - Mini Project: Build & Apply

Choose your learning style9 modes available
Low-level caching with Rails.cache
📖 Scenario: You are building a simple Rails app that fetches and displays product prices. To make the app faster, you want to store the prices temporarily in a cache so the app doesn't have to fetch them every time.
🎯 Goal: Build a small Rails code snippet that uses Rails.cache to store and retrieve product prices, improving speed by avoiding repeated calculations.
📋 What You'll Learn
Create a hash called product_prices with exact product-price pairs
Create a variable called cache_key with the value "product_prices_cache"
Use Rails.cache.fetch with cache_key to store product_prices if not cached
Add an expiration time of 5 minutes to the cache fetch
💡 Why This Matters
🌍 Real World
Caching is used in web apps to speed up repeated data access by storing results temporarily.
💼 Career
Understanding Rails low-level caching helps backend developers optimize app performance and reduce database load.
Progress0 / 4 steps
1
Create the product prices hash
Create a hash called product_prices with these exact entries: "apple" => 100, "banana" => 50, "orange" => 75.
Ruby on Rails
Need a hint?

Use Ruby hash syntax with string keys and integer values.

2
Set the cache key
Create a variable called cache_key and set it to the string "product_prices_cache".
Ruby on Rails
Need a hint?

Just assign the string to the variable.

3
Fetch or store product prices in cache
Use Rails.cache.fetch with cache_key to get the cached product prices. If the cache is empty, store product_prices in the cache.
Ruby on Rails
Need a hint?

Use a block with Rails.cache.fetch to provide the value if cache is empty.

4
Add expiration time to cache fetch
Modify the Rails.cache.fetch call to add an expiration time of 5 minutes using the expires_in option.
Ruby on Rails
Need a hint?

Pass expires_in: 5.minutes as a second argument to Rails.cache.fetch.