From 0b25a08a1705b074f0140bca28093c6fd17a8226 Mon Sep 17 00:00:00 2001 From: dolzenko Date: Tue, 2 Mar 2010 01:08:29 +0300 Subject: [PATCH] Make FileStore#exist? consistent with FileStore#read when :expires_in option is supplied --- .../lib/active_support/cache/file_store.rb | 13 +++++++++++-- activesupport/test/caching_test.rb | 20 ++++++++++++++++++++ 2 files changed, 31 insertions(+), 2 deletions(-) diff --git a/activesupport/lib/active_support/cache/file_store.rb b/activesupport/lib/active_support/cache/file_store.rb index 7f34cb5..b56e5ee 100644 --- a/activesupport/lib/active_support/cache/file_store.rb +++ b/activesupport/lib/active_support/cache/file_store.rb @@ -10,7 +10,12 @@ module ActiveSupport def read(name, options = nil) super - File.open(real_file_path(name), 'rb') { |f| Marshal.load(f) } rescue nil + file_name = real_file_path(name) + expires = expires_in(options) + + if exist_without_instrument?(file_name, expires) + File.open(file_name, 'rb') { |f| Marshal.load(f) } + end end def write(name, value, options = nil) @@ -44,7 +49,7 @@ module ActiveSupport def exist?(name, options = nil) super - File.exist?(real_file_path(name)) + exist_without_instrument?(real_file_path(name), expires_in(options)) end private @@ -67,6 +72,10 @@ module ActiveSupport end end end + + def exist_without_instrument?(file_name, expires) + File.exist?(file_name) && (expires <= 0 || Time.now - File.mtime(file_name) < expires) + end end end end diff --git a/activesupport/test/caching_test.rb b/activesupport/test/caching_test.rb index eed65d4..4ee06ca 100644 --- a/activesupport/test/caching_test.rb +++ b/activesupport/test/caching_test.rb @@ -154,6 +154,26 @@ class FileStoreTest < ActiveSupport::TestCase end include CacheStoreBehavior + def test_expires_in + time = Time.local(2008, 4, 24) + Time.stubs(:now).returns(time) + File.stubs(:mtime).returns(time) + + @cache.write('foo', 'bar') + cache_read = lambda { @cache.read('foo', :expires_in => 60) } + cache_exists = lambda { @cache.exist?('foo', :expires_in => 60) } + + assert_equal 'bar', cache_read.call + assert_equal true, cache_exists.call + + Time.stubs(:now).returns(time + 30) + assert_equal 'bar', cache_read.call + assert_equal true, cache_exists.call + + Time.stubs(:now).returns(time + 120) + assert_nil cache_read.call + assert_equal false, cache_exists.call + end end class MemoryStoreTest < ActiveSupport::TestCase -- 1.6.0.4