Skip to content

Commit

Permalink
pass the key to the block in cache.fetch on misses
Browse files Browse the repository at this point in the history
  • Loading branch information
noahhendrix committed Oct 23, 2012
1 parent 4049643 commit 81b7112
Show file tree
Hide file tree
Showing 2 changed files with 12 additions and 7 deletions.
10 changes: 5 additions & 5 deletions activesupport/lib/active_support/cache.rb
Expand Up @@ -182,10 +182,10 @@ def self.instrument
# 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 run
# 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.
# 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"
Expand Down Expand Up @@ -300,7 +300,7 @@ def fetch(name, options = nil)
entry.value
else
result = instrument(:generate, name, options) do |payload|
yield
yield(name)
end
write(name, result, options)
result
Expand Down
9 changes: 7 additions & 2 deletions activesupport/test/caching_test.rb
Expand Up @@ -83,7 +83,7 @@ def test_expand_cache_key_of_false
def test_expand_cache_key_of_true
assert_equal 'true', ActiveSupport::Cache.expand_cache_key(true)
end

def test_expand_cache_key_of_array_like_object
assert_equal 'foo/bar/baz', ActiveSupport::Cache.expand_cache_key(%w{foo bar baz}.to_enum)
end
Expand Down Expand Up @@ -197,6 +197,11 @@ def test_fetch_with_cache_miss
assert_equal 'baz', @cache.fetch('foo') { 'baz' }
end

def test_fetch_with_cache_miss_passes_key_to_block
@cache.expects(:write).with('foo', 3, @cache.options)
assert_equal 3, @cache.fetch('foo') { |key| key.length }
end

def test_fetch_with_forced_cache_miss
@cache.write('foo', 'bar')
@cache.expects(:read).never
Expand Down Expand Up @@ -594,7 +599,7 @@ def test_key_transformation_with_pathname
assert_equal "views/index?id=1", @cache_with_pathname.send(:file_path_key, key)
end

# Test that generated cache keys are short enough to have Tempfile stuff added to them and
# Test that generated cache keys are short enough to have Tempfile stuff added to them and
# remain valid
def test_filename_max_size
key = "#{'A' * ActiveSupport::Cache::FileStore::FILENAME_MAX_SIZE}"
Expand Down

0 comments on commit 81b7112

Please sign in to comment.