Complete the code to write data to the cache with a key.
Rails.cache.[1]("user_1", "John")
read instead of write to store data.fetch when you want to just write without reading.The write method stores data in the cache under the given key.
Complete the code to read cached data by key.
user_name = Rails.cache.[1]("user_1")
write instead of read to get data.fetch when only reading is needed.The read method retrieves data from the cache by key.
Fix the error in the code to fetch cached data or compute and store it.
user_name = Rails.cache.[1]("user_1") { "John" }
read which does not accept a block.write which does not read existing data.The fetch method reads cached data if present; otherwise, it runs the block, stores the result, and returns it.
Fill both blanks to write data with expiration time in seconds.
Rails.cache.write("session_123", "active", expires_in: [1].[2])
The expires_in option sets how long the cache entry lasts. Here, 5 seconds means the data expires quickly.
Fill all three blanks to fetch cached data with a block and set expiration.
user = Rails.cache.fetch("user_42", expires_in: [1].[2]) { [3] }
This code fetches user data from cache or runs User.find(42) to get it, caching it for 10 minutes (600 seconds).