Performance: Low-level caching with Rails.cache
Improves page load speed by storing and reusing expensive data or computations, reducing database queries and server processing time.
def expensive_data Rails.cache.fetch('expensive_data_key', expires_in: 10.minutes) do Model.where(condition: true).to_a end end
def expensive_data
Model.where(condition: true).to_a
end| Pattern | DOM Operations | Reflows | Paint Cost | Verdict |
|---|---|---|---|---|
| No caching, query on every request | N/A (server-side) | N/A | N/A | [X] Bad |
| Using Rails.cache to store query results | N/A (server-side) | N/A | N/A | [OK] Good |
Rails.cache in a Rails application?Rails.cache doesRails.cache provides a way to store and retrieve data quickly in memory or other stores.Rails.cache?fetch method usageRails.cache.fetch(:key) { block } tries to read the key, or runs the block and stores the result if missing.get, store, and read do not accept a block to compute missing values automatically.Rails.cache.fetch('counter') call?count = 0
Rails.cache.fetch('counter') do
count += 1
end
puts Rails.cache.fetch('counter')Rails.cache.fetch('user_1') do
User.find(1)
end
Rails.cache.write('user_1')write method usageRails.cache.write requires a key and a value; here only the key is given, missing the value argument.User.find; write order is not mandatory here.Rails.cache.fetch?expires_in: 10.minutes is the correct option to set cache expiration time in fetch.expires and timeout are not valid options; write can set expiration but fetch with block is preferred for caching computed data.Pass the test and this pattern moves unknown