Method: ActiveSupport::Cache::Store#fetch
- Defined in:
- activesupport/lib/active_support/cache.rb
#fetch(name, options = nil, &block) ⇒ Object
Fetches data from the cache, using the given key. If there is data in the cache with the given key, then that data is returned.
If there is no such data in the cache (a cache miss), then nil will be returned. However, if a block has been passed, that block will be passed the key and executed in the event of a cache miss. The return value of the block will be written to the cache under the given cache key, and that return value will be returned.
cache.write('today', 'Monday')
cache.fetch('today') # => "Monday"
cache.fetch('city') # => nil
cache.fetch('city') do
'Duckburgh'
end
cache.fetch('city') # => "Duckburgh"
Options
Internally, fetch calls read_entry, and calls write_entry on a cache miss. Thus, fetch supports the same options as #read and #write. Additionally, fetch supports the following options:
-
force: true- Forces a cache “miss,” meaning we treat the cache value as missing even if it’s present. Passing a block is required whenforceis true so this always results in a cache write.cache.write('today', 'Monday') cache.fetch('today', force: true) { 'Tuesday' } # => 'Tuesday' cache.fetch('today', force: true) # => ArgumentErrorThe
:forceoption is useful when you’re calling some other method to ask whether you should force a cache write. Otherwise, it’s clearer to just callwrite. -
skip_nil: true- Prevents caching a nil result:cache.fetch('foo') { nil } cache.fetch('bar', skip_nil: true) { nil } cache.exist?('foo') # => true cache.exist?('bar') # => false -
:race_condition_ttl- Specifies the number of seconds during which an expired value can be reused while a new value is being generated. This can be used to prevent race conditions when cache entries expire, by preventing multiple processes from simultaneously regenerating the same entry (also known as the dog pile effect).When a process encounters a cache entry that has expired less than
:race_condition_ttlseconds ago, it will bump the expiration time by:race_condition_ttlseconds before generating a new value. During this extended time window, while the process generates a new value, other processes will continue to use the old value. After the first process writes the new value, other processes will then use it.If the first process errors out while generating a new value, another process can try to generate a new value after the extended time window has elapsed.
# Set all values to expire after one second. cache = ActiveSupport::Cache::MemoryStore.new(expires_in: 1) cache.write("foo", "original value") val_1 = nil val_2 = nil p cache.read("foo") # => "original value" sleep 1 # wait until the cache expires t1 = Thread.new do # fetch does the following: # 1. gets an recent expired entry # 2. extends the expiry by 2 seconds (race_condition_ttl) # 3. regenerates the new value val_1 = cache.fetch("foo", race_condition_ttl: 2) do sleep 1 "new value 1" end end # Wait until t1 extends the expiry of the entry # but before generating the new value sleep 0.1 val_2 = cache.fetch("foo", race_condition_ttl: 2) do # This block won't be executed because t1 extended the expiry "new value 2" end t1.join p val_1 # => "new value 1" p val_2 # => "original value" p cache.fetch("foo") # => "new value 1" # The entry requires 3 seconds to expire (expires_in + race_condition_ttl) # We have waited 2 seconds already (sleep(1) + t1.join) thus we need to wait 1 # more second to see the entry expire. sleep 1 p cache.fetch("foo") # => nil
Dynamic Options
In some cases it may be necessary to dynamically compute options based on the cached value. To support this, an ActiveSupport::Cache::WriteOptions instance is passed as the second argument to the block. For example:
cache.fetch("authentication-token:#{user.id}") do |key, |
token = authenticate_to_service
.expires_at = token.expires_at
token
end
444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 |
# File 'activesupport/lib/active_support/cache.rb', line 444 def fetch(name, = nil, &block) if block_given? = () key = normalize_key(name, ) entry = nil unless [:force] instrument(:read, key, ) do |payload| cached_entry = read_entry(key, **, event: payload) entry = handle_expired_entry(cached_entry, key, ) if entry if entry.mismatched?(normalize_version(name, )) entry = nil else begin entry.value rescue DeserializationError entry = nil end end end payload[:super_operation] = :fetch if payload payload[:hit] = !!entry if payload end end if entry get_entry_value(entry, name, ) else save_block_result_to_cache(name, key, , &block) end elsif && [:force] raise ArgumentError, "Missing block: Calling `Cache#fetch` with `force: true` requires a block." else read(name, ) end end |