From a712acc42543b575a623e1a8880c0e9dd5505cfa Mon Sep 17 00:00:00 2001 From: Santosh Wadghule Date: Sat, 16 Apr 2016 16:16:17 +0530 Subject: [PATCH] Fix forced cache miss for fetch. - Raised an argument error if no block is passed to #fetch with 'force: true' option is set. - Added tests for the same. --- activesupport/CHANGELOG.md | 7 +++++++ activesupport/lib/active_support/cache.rb | 12 ++++++++++-- activesupport/test/caching_test.rb | 14 ++++++++++++++ 3 files changed, 31 insertions(+), 2 deletions(-) diff --git a/activesupport/CHANGELOG.md b/activesupport/CHANGELOG.md index b2ab5ffcbe..690314b59a 100644 --- a/activesupport/CHANGELOG.md +++ b/activesupport/CHANGELOG.md @@ -1,3 +1,10 @@ +* Raise an argument error if no block is passed to #fetch with option + `force: true` is set. + + cache.fetch('today', force: true) # => ArgumentError: Missing block + + *Santosh Wadghule* + * `ActiveSupport::Duration` supports weeks and hours. [1.hour.inspect, 1.hour.value, 1.hour.parts] diff --git a/activesupport/lib/active_support/cache.rb b/activesupport/lib/active_support/cache.rb index 85f462a1b1..f27bac3dca 100644 --- a/activesupport/lib/active_support/cache.rb +++ b/activesupport/lib/active_support/cache.rb @@ -198,10 +198,16 @@ def mute # cache.fetch('city') # => "Duckburgh" # # You may also specify additional options via the +options+ argument. - # Setting force: true will force a cache miss: + # Setting force: true will force a cache miss and return value of + # the block will be written to the cache under the given cache key. # # cache.write('today', 'Monday') - # cache.fetch('today', force: true) # => nil + # cache.fetch('today', force: true) { 'Tuesday' } # => 'Tuesday' + # + # It will raise an argument error if no block is passed to #fetch with + # option force: true is set. + # + # cache.fetch('today', force: true) # => ArgumentError: Missing block # # Setting :compress will store a large cache entry set by the call # in a compressed format. @@ -292,6 +298,8 @@ def fetch(name, options = nil) else save_block_result_to_cache(name, options) { |_name| yield _name } end + elsif options && options[:force] + raise ArgumentError, 'Missing block' else read(name, options) end diff --git a/activesupport/test/caching_test.rb b/activesupport/test/caching_test.rb index 9e744afb2b..032367e10d 100644 --- a/activesupport/test/caching_test.rb +++ b/activesupport/test/caching_test.rb @@ -266,6 +266,20 @@ def test_fetch_with_cached_nil end end + def test_fetch_with_forced_cache_miss_with_block + @cache.write('foo', 'bar') + assert_equal 'foo_bar', @cache.fetch('foo', force: true) { 'foo_bar' } + end + + def test_fetch_with_forced_cache_miss_without_block + @cache.write('foo', 'bar') + assert_raises(ArgumentError, 'Missing block') do + @cache.fetch('foo', force: true) + end + + assert_equal 'bar', @cache.read('foo') + end + def test_should_read_and_write_hash assert @cache.write('foo', {:a => "b"}) assert_equal({:a => "b"}, @cache.read('foo')) -- GitLab