| Class | Cache |
| In: |
lib/cache.rb
|
| Parent: | Object |
| REPOSITORY | = | '/var/cache/ruby_ex_cache' | Constants | |
| MAX_SIZE | = | 50 * 1024 * 1024 | ||
| BLOCK_SIZE | = | 1024 |
| max_size | [R] | Attributs |
| repository | [R] | Attributs |
| size | [R] | Attributs |
Constructor
# File lib/cache.rb, line 29 def initialize(repository=REPOSITORY, max_size=MAX_SIZE) @repository = Pathname.new(repository) @max_size = check_max_size(max_size) create end
# File lib/cache.rb, line 54 def clear @repository.each_entry do |p| (@repository + p).delete unless p.to_s =~ /^\./ end @size = 0 @atime.clear end
Methods
# File lib/cache.rb, line 38 def create @size = 0 @atime = [] if @repository.directory? @repository.each_entry do |p| next if p.to_s =~ /^\./ full_p = @repository + p @atime << full_p @size += full_p.size end @atime.sort! { |a, b| a.atime <=> b.atime } else @repository.mkdir end end
# File lib/cache.rb, line 118 def export(md5sum, dst_filename) p = @repository + md5sum.to_s FileUtils.copy_entry(p, dst_filename) update_entry(p) p end
# File lib/cache.rb, line 109 def import(filename) p = nil pathname = filename.to_path pathname.open do |f| p = write(pathname.stat.mode) { f.eof? ? nil : f.read(BLOCK_SIZE) } end p end
# File lib/cache.rb, line 138 def max_size=(max_size) @max_size = check_max_size(max_size) adjust_size end
# File lib/cache.rb, line 67 def open(md5sum=nil, mode='r', perm=0644, &block) case mode when 'r': read(md5sum, &block) when 'w': write(perm, &block) else raise(ArgumentError, "`#{mode}' - bad mode") end end
# File lib/cache.rb, line 125 def present?(md5sum) p = @repository + md5sum.to_s p.exist? ? p : nil; end
# File lib/cache.rb, line 76 def read(md5sum, &block) p = @repository + md5sum.to_s p.open('r', &block) @atime.delete(p) @atime << p p end
# File lib/cache.rb, line 84 def write(perm=0644, &block) TempPath.new('cache_file') do |tmp| md5 = Digest::MD5.new new_size = 0 tmp.open('w') do |out| while (str = block[]) out.write(str) md5 << str new_size += str.size end end p = @repository + md5.to_s if p.exist? @atime.delete(p) else @size += new_size end FileUtils.move(tmp.to_s, p.to_s) p.chmod(perm) @atime << p adjust_size p end end
# File lib/cache.rb, line 148 def adjust_size while @size > @max_size p = @atime.shift @size -= p.size p.delete end @size end