Bird
Raised Fist0
Ruby on Railsframework~20 mins

Low-level caching with Rails.cache - Practice Problems & Coding Challenges

Choose your learning style10 modes available
Challenge - 5 Problems
🎖️
Rails Cache Master
Get all challenges correct to earn this badge!
Test your skills under time pressure!
❓ component_behavior
intermediate
2:00remaining
What does this Rails.cache.fetch block return?
Consider this code snippet in a Rails controller action:
value = Rails.cache.fetch('user_count', expires_in: 5.minutes) do
  User.count
end
What will value contain if the cache is empty?
Ruby on Rails
value = Rails.cache.fetch('user_count', expires_in: 5.minutes) do
  User.count
end
AThe current count of User records from the database, and it caches this value for 5 minutes.
BAlways nil because the cache key 'user_count' does not exist yet.
CAn error because the block is missing a return statement.
DThe string 'User.count' is cached and returned as a string.
Attempts:
2 left
💡 Hint
Think about what Rails.cache.fetch does when the key is missing.
📝 Syntax
intermediate
2:00remaining
Identify the syntax error in this Rails.cache.write usage
Which option shows the correct syntax to write a value to cache with a 10-minute expiration?
Ruby on Rails
Rails.cache.write('key', 'value', expires_in: 10.minutes)
ARails.cache.write('key', value: 'value', expires_in: 10.minutes)
BRails.cache.write('key', 'value', expire_in: 10.minutes)
CRails.cache.write('key', 'value', expires_in: 10.minutes)
DRails.cache.write('key', 'value', expires: 10.minutes)
Attempts:
2 left
💡 Hint
Check the exact option name for expiration time.
🔧 Debug
advanced
2:00remaining
Why does this Rails.cache.fetch block never update the cached value?
Given this code:
Rails.cache.fetch('random_number', expires_in: 1.minute) do
  rand(100)
end

Why does the cached value never change even after 1 minute?
Ruby on Rails
Rails.cache.fetch('random_number', expires_in: 1.minute) do
  rand(100)
end
AThe block is never executed because the key always exists in cache until manually deleted.
BThe expires_in option is ignored because it must be passed as a string, not a symbol.
CThe cache key is misspelled, so it fetches a different key each time.
DThe cache store does not support expiration, so the value stays forever.
Attempts:
2 left
💡 Hint
Think about the cache store configuration and expiration support.
❓ state_output
advanced
2:00remaining
What is the output of this Rails.cache.fetch with race_condition_ttl?
Consider this code snippet:
value = Rails.cache.fetch('expensive_calc', expires_in: 10.seconds, race_condition_ttl: 5.seconds) do
  sleep 2
  Time.now.to_i
end
puts value

If two requests run this code at the same time after the cache expired, what will happen?
Ruby on Rails
value = Rails.cache.fetch('expensive_calc', expires_in: 10.seconds, race_condition_ttl: 5.seconds) do
  sleep 2
  Time.now.to_i
end
puts value
ABoth requests recompute the value simultaneously causing duplicate work.
BThe first request recomputes and caches the new time; the second request returns the old cached value during recomputation.
CBoth requests return nil because the cache expired and block is not executed.
DThe code raises an error because race_condition_ttl is not a valid option.
Attempts:
2 left
💡 Hint
Race condition TTL helps avoid multiple recomputations at once.
🧠 Conceptual
expert
2:00remaining
Which cache store supports distributed caching in Rails by default?
You want to share cached data across multiple Rails app servers. Which cache store should you choose?
AMemCacheStore
BFileStore
CMemoryStore
DNullStore
Attempts:
2 left
💡 Hint
Distributed caching means multiple servers share the same cache data.

Practice

(1/5)
1. What is the main purpose of using Rails.cache in a Rails application?
easy
A. To permanently save data to the database
B. To store data temporarily for faster repeated access
C. To send emails asynchronously
D. To handle user authentication

Solution

  1. Step 1: Understand the role of caching

    Caching stores data temporarily to avoid repeating expensive operations.
  2. Step 2: Identify what Rails.cache does

    Rails.cache provides a way to store and retrieve data quickly in memory or other stores.
  3. Final Answer:

    To store data temporarily for faster repeated access -> Option B
  4. Quick Check:

    Caching = Temporary storage for speed [OK]
Hint: Caching speeds up repeated data access by storing it temporarily [OK]
Common Mistakes:
  • Confusing caching with permanent database storage
  • Thinking caching handles user login
  • Assuming caching sends emails
2. Which of the following is the correct syntax to fetch a cached value or compute and store it if missing using Rails.cache?
easy
A. Rails.cache.store(:key, expensive_method)
B. Rails.cache.get(:key) { expensive_method }
C. Rails.cache.fetch(:key) { expensive_method }
D. Rails.cache.read(:key) { expensive_method }

Solution

  1. Step 1: Recall the fetch method usage

    Rails.cache.fetch(:key) { block } tries to read the key, or runs the block and stores the result if missing.
  2. Step 2: Check other options for correctness

    get, store, and read do not accept a block to compute missing values automatically.
  3. Final Answer:

    Rails.cache.fetch(:key) { expensive_method } -> Option C
  4. Quick Check:

    Use fetch with block to cache missing data [OK]
Hint: Use fetch with a block to cache or compute missing data [OK]
Common Mistakes:
  • Using read or get which don't accept blocks
  • Trying to use store with a block
  • Confusing fetch with read
3. Given the code below, what will be printed by the second Rails.cache.fetch('counter') call?
count = 0
Rails.cache.fetch('counter') do
  count += 1
end
puts Rails.cache.fetch('counter')
medium
A. nil
B. 0
C. 2
D. 1

Solution

  1. Step 1: Understand the first fetch call

    The block runs because 'counter' key is missing, so count increments from 0 to 1 and stores 1.
  2. Step 2: Understand the second fetch call

    The key 'counter' exists now, so fetch returns cached value 1 without running the block.
  3. Final Answer:

    1 -> Option D
  4. Quick Check:

    Cached value returned without block run = 1 [OK]
Hint: Cached value returns without running block again [OK]
Common Mistakes:
  • Assuming block runs every time
  • Thinking count resets to 0
  • Expecting nil if key exists
4. Identify the error in this caching code snippet:
Rails.cache.fetch('user_1') do
  User.find(1)
end
Rails.cache.write('user_1')
medium
A. Calling write without a value argument causes an error
B. fetch block should not call User.find
C. The cache key must be a symbol, not a string
D. write should be called before fetch

Solution

  1. Step 1: Analyze the write method usage

    Rails.cache.write requires a key and a value; here only the key is given, missing the value argument.
  2. Step 2: Check other options for validity

    Using string keys is valid; fetch block can call User.find; write order is not mandatory here.
  3. Final Answer:

    Calling write without a value argument causes an error -> Option A
  4. Quick Check:

    write needs key and value [OK]
Hint: write needs both key and value arguments [OK]
Common Mistakes:
  • Omitting value in write method
  • Thinking keys must be symbols
  • Misunderstanding fetch block usage
5. You want to cache a list of products but ensure the cache expires after 10 minutes. Which is the correct way to do this with Rails.cache.fetch?
hard
A. Rails.cache.fetch('products', expires_in: 10.minutes) { Product.all.to_a }
B. Rails.cache.fetch('products', expires: 10) { Product.all }
C. Rails.cache.write('products', Product.all, expires_in: 600)
D. Rails.cache.fetch('products', timeout: 600) { Product.all.to_a }

Solution

  1. Step 1: Identify correct option for expiration

    expires_in: 10.minutes is the correct option to set cache expiration time in fetch.
  2. Step 2: Check other options for correctness

    expires and timeout are not valid options; write can set expiration but fetch with block is preferred for caching computed data.
  3. Final Answer:

    Rails.cache.fetch('products', expires_in: 10.minutes) { Product.all.to_a } -> Option A
  4. Quick Check:

    Use expires_in with fetch for expiration [OK]
Hint: Use expires_in option with fetch to set cache lifetime [OK]
Common Mistakes:
  • Using wrong option names like expires or timeout
  • Not converting ActiveRecord relation to array
  • Using write instead of fetch with block
Recommended

Ready to prove it?

Pass the test and this pattern moves unknown strong while earning +1 Grip toward your certificate.

10 questions~5 mineasy hard