Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Fix forced cache miss for fetch. #24577

Merged
merged 1 commit into from
Apr 18, 2016
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Jump to
Jump to file
Failed to load files.
Diff view
Diff view
7 changes: 7 additions & 0 deletions activesupport/CHANGELOG.md
Original file line number Diff line number Diff line change
@@ -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]
Expand Down
12 changes: 10 additions & 2 deletions activesupport/lib/active_support/cache.rb
Original file line number Diff line number Diff line change
Expand Up @@ -198,10 +198,16 @@ def mute
# cache.fetch('city') # => "Duckburgh"
#
# You may also specify additional options via the +options+ argument.
# Setting <tt>force: true</tt> will force a cache miss:
# Setting <tt>force: true</tt> 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 <tt>force: true</tt> is set.
#
# cache.fetch('today', force: true) # => ArgumentError: Missing block
#
# Setting <tt>:compress</tt> will store a large cache entry set by the call
# in a compressed format.
Expand Down Expand Up @@ -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
Expand Down
14 changes: 14 additions & 0 deletions activesupport/test/caching_test.rb
Original file line number Diff line number Diff line change
Expand Up @@ -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'))
Expand Down