class Ruby::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
Attributes
coding[R]
dir[R]
expiration_time[R]
ext[R]
Public Class Methods
new(dir, filename, options = {})
click to toggle source
# File lib/ruby/reports/cache_file.rb, line 13 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/ruby/reports/cache_file.rb, line 47 def clear FileUtils.rm_f(@filename) end
exists?()
click to toggle source
# File lib/ruby/reports/cache_file.rb, line 23 def exists? !expired?(@filename) end
Also aliased as: ready?
filename()
click to toggle source
# File lib/ruby/reports/cache_file.rb, line 28 def filename fail 'File doesn\'t exist, check exists? before' unless exists? @filename end
open(force = false) { |tempfile| ... }
click to toggle source
# File lib/ruby/reports/cache_file.rb, line 33 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/ruby/reports/cache_file.rb, line 77 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/ruby/reports/cache_file.rb, line 66 def clear_expired_files # TODO: avoid races when worker building # his report longer than @expiration_time FileUtils.rm_f cache_files_array.select { |fname| expired?(fname) } end
expired?(fname)
click to toggle source
# File lib/ruby/reports/cache_file.rb, line 72 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/ruby/reports/cache_file.rb, line 61 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/ruby/reports/cache_file.rb, line 53 def with_tempfile yield(tempfile = Tempfile.new(Digest::MD5.hexdigest(@filename), :encoding => coding)) ensure return unless tempfile tempfile.close unless tempfile.closed? tempfile.unlink end