From c98177ea202fbc37681ab020c12b2eb83cb51cef Mon Sep 17 00:00:00 2001 From: ethicalhack3r Date: Fri, 15 Nov 2013 00:24:20 +0100 Subject: [PATCH] Create unique cache dir to prevent race conditions. Issue #344. --- lib/common/cache_file_store.rb | 11 +++++++++-- spec/lib/common/cache_file_store_spec.rb | 22 +++++++++++++++++----- 2 files changed, 26 insertions(+), 7 deletions(-) diff --git a/lib/common/cache_file_store.rb b/lib/common/cache_file_store.rb index 6f7cf2ec..e1327f8c 100644 --- a/lib/common/cache_file_store.rb +++ b/lib/common/cache_file_store.rb @@ -18,8 +18,8 @@ class CacheFileStore # YAML is Human Readable, contrary to Marshal which store in a binary format # Marshal does not need any "require" def initialize(storage_path, serializer = Marshal) - @storage_path = File.expand_path(storage_path) - @serializer = serializer + @storage_path = File.expand_path(storage_path + '/' + storage_dir) + @serializer = serializer # File.directory? for ruby <= 1.9 otherwise, # it makes more sense to do Dir.exist? :/ @@ -58,4 +58,11 @@ class CacheFileStore File::join(@storage_path, key) end + def storage_dir + time = Time.now + random = (0...8).map { (65 + rand(26)).chr }.join + + Digest::MD5.hexdigest("#{time}#{random}") + end + end diff --git a/spec/lib/common/cache_file_store_spec.rb b/spec/lib/common/cache_file_store_spec.rb index e7687237..def5df67 100644 --- a/spec/lib/common/cache_file_store_spec.rb +++ b/spec/lib/common/cache_file_store_spec.rb @@ -17,13 +17,13 @@ describe CacheFileStore do describe '#storage_path' do it 'returns the storage path given in the #new' do - @cache.storage_path.should == cache_dir + @cache.storage_path.should match(/#{cache_dir}/) end end describe '#serializer' do it 'should return the default serializer : Marshal' do - @cache.serializer.should == Marshal + @cache.serializer.should == Marshal @cache.serializer.should_not == YAML end end @@ -32,12 +32,12 @@ describe CacheFileStore do it "should remove all files from the cache dir (#{@cache_dir}" do # let's create some files into the directory first (0..5).each do |i| - File.new(cache_dir + "/file_#{i}.txt", File::CREAT) + File.new(@cache.storage_path + "/file_#{i}.txt", File::CREAT) end - count_files_in_dir(cache_dir, 'file_*.txt').should == 6 + count_files_in_dir(@cache.storage_path, 'file_*.txt').should == 6 @cache.clean - count_files_in_dir(cache_dir).should == 0 + count_files_in_dir(@cache.storage_path).should == 0 end end @@ -70,4 +70,16 @@ describe CacheFileStore do ## TODO write / read for an object end + + describe '#storage_dir' do + it 'should create a unique storage dir' do + storage_dirs = [] + + (1..5).each do |i| + storage_dirs << CacheFileStore.new(cache_dir).storage_path + end + + storage_dirs.uniq.size.should == 5 + end + end end