class Resque::Reports::CacheFile
Class describes how to storage and access cache file NOTE: Every time any cache file is opening,
cache is cleared from old files.
Constants
- DEFAULT_CODING
- DEFAULT_EXPIRE_TIME
Public Class Methods
new(dir, filename, options = {})
click to toggle source
# File lib/resque/reports/cache_file.rb, line 14 def initialize(dir, filename, options = {}) @dir = dir @filename = File.join(dir, filename) @ext = File.extname(filename) # options @coding = options[:coding] || DEFAULT_CODING @expiration_time = options[:expire_in] || DEFAULT_EXPIRE_TIME end
Public Instance Methods
clear()
click to toggle source
# File lib/resque/reports/cache_file.rb, line 48 def clear FileUtils.rm_f(@filename) end
exists?()
click to toggle source
# File lib/resque/reports/cache_file.rb, line 24 def exists? !expired?(@filename) end
Also aliased as: ready?
filename()
click to toggle source
# File lib/resque/reports/cache_file.rb, line 29 def filename fail 'File doesn\'t exists, check exists? before' unless exists? @filename end
open(force = false) { |tempfile| ... }
click to toggle source
# File lib/resque/reports/cache_file.rb, line 34 def open(force = false) prepare_cache_dir (force ? clear : return) if File.exists?(@filename) with_tempfile do |tempfile| yield tempfile tempfile.close FileUtils.cp(tempfile.path, @filename) FileUtils.chmod(0644, @filename) end end
Protected Instance Methods
cache_files_array()
click to toggle source
# File lib/resque/reports/cache_file.rb, line 83 def cache_files_array Dir.new(@dir) .map { |fname| File.join(@dir, fname) if File.extname(fname) == @ext } .compact end
clear_expired_files()
click to toggle source
# File lib/resque/reports/cache_file.rb, line 69 def clear_expired_files # TODO: avoid races when worker building # his report longer than @expiration_time files_to_delete = cache_files_array.select { |fname| expired?(fname) } FileUtils.rm_f files_to_delete end
expired?(fname)
click to toggle source
# File lib/resque/reports/cache_file.rb, line 77 def expired?(fname) return true unless File.file?(fname) File.mtime(fname) + @expiration_time < Time.now end
prepare_cache_dir()
click to toggle source
# File lib/resque/reports/cache_file.rb, line 63 def prepare_cache_dir FileUtils.mkdir_p @dir # create folder if not exists clear_expired_files end
with_tempfile() { |tempfile = tempfile(hexdigest, :encoding => coding)| ... }
click to toggle source
# File lib/resque/reports/cache_file.rb, line 54 def with_tempfile yield(tempfile = Tempfile.new(Digest::MD5.hexdigest(@filename), :encoding => @coding)) ensure if tempfile tempfile.close unless tempfile.closed? tempfile.unlink end end