diff --git a/lib/acts_as_indexed/storage.rb b/lib/acts_as_indexed/storage.rb index 2bfe8a3..12d399e 100644 --- a/lib/acts_as_indexed/storage.rb +++ b/lib/acts_as_indexed/storage.rb @@ -155,35 +155,41 @@ def encode_character(char) end def write_file(file_path) - new_file = file_path.to_s - tmp_file = new_file + TEMP_FILE_EXTENSION + new_file_name = file_path.to_s + temp_file_name = new_file_name + TEMP_FILE_EXTENSION # Windows doesn't seem to play nice with writing then moving the file. # https://github.com/dougal/acts_as_indexed/issues/15 - writeable_file = windows? ? new_file : tmp_file + writeable_file = windows? ? new_file_name : temp_file_name File.open(writeable_file, 'w+') do |f| yield(f) end - FileUtils.mv(tmp_file, new_file) unless windows? + FileUtils.mv(temp_file_name, new_file_name) unless windows? end + @@file_lock = Mutex.new + # Borrowed from Rails' ActiveSupport FileStore. Also under MIT licence. - # Lock a file for a block so only one process can modify it at a time. + # Lock a file for a block so only one process or thread can modify it at a time. def lock_file(file_path, &block) # :nodoc: - # Windows does not support file locking. - if !windows? && file_path.exist? - file_path.open('r+') do |f| - begin - f.flock File::LOCK_EX - yield - ensure - f.flock File::LOCK_UN + @@file_lock.synchronize do + + # Windows does not support file locking. + if !windows? && file_path.exist? + file_path.open('r+') do |f| + begin + f.flock File::LOCK_EX + yield + ensure + f.flock File::LOCK_UN + end end + else + yield end - else - yield + end end