Sha256: 719d78db5ba37f39b4a32d0ac16a8c46a8fc48c7db27286f7e861b5b03ef33b0

Contents?: true

Size: 1.76 KB

Versions: 352

Compression:

Stored size: 1.76 KB

Contents

require 'fileutils'
require 'rbbt/util/misc'

# Provides caching functionality for files downloaded from the internet
module FileCache
  CACHEDIR = "/tmp/rbbt_cache" 
  begin
    FileUtils.mkdir(CACHEDIR)
  rescue
  end unless File.exist? CACHEDIR


  def self.cachedir=(cachedir)
    CACHEDIR.replace cachedir
    FileUtils.mkdir_p CACHEDIR unless File.exist? CACHEDIR
  end

  def self.cachedir
    CACHEDIR
  end

  def self.path(filename)
    filename = File.basename filename

    filename.match(/(.+)\.(.+)/)

    base = filename.sub(/\..+/,'')
    dirs = base.scan(/./).reverse.values_at(0,1,2,3,4).compact

    File.join(File.join(CACHEDIR, *dirs), filename) 
  end

  def self.add(filename, content)
    path = path(filename)
    
    FileUtils.makedirs(File.dirname(path), :mode => 0777)

    Misc.sensiblewrite(path, content)

    FileUtils.chmod 0666, path

    path
  end

  def self.found(filename)
    File.exist? FileCache.path(filename)
  end

  def self.get(filename)
    path = path(filename)

    return nil if ! File.exist? path

    File.open(path)
  end

  def self.del(filename)
    path = path(filename)

    FileUtils.rm path if File.exist? path
  end

  def self.cache_online_elements(ids, pattern = nil, &block)
    ids = [ids] unless Array === ids

    result_files = {}
    missing = []
    ids.each do |id|
      filename = pattern ? pattern.sub("{ID}", id.to_s) : id.to_s

      if FileCache.found(filename)
        result_files[id] = FileCache.path(filename)
      else
        missing << id
      end
    end

    yield(missing).each do |id, content|
      filename = pattern ? pattern.sub("{ID}", id.to_s) : id.to_s
      path = FileCache.path(filename)
      Open.write(path, content)
      result_files[id] = path
    end if missing.any?

    result_files
  end
end

Version data entries

352 entries across 352 versions & 1 rubygems

Version Path
rbbt-util-5.34.17 lib/rbbt/util/filecache.rb
rbbt-util-5.34.16 lib/rbbt/util/filecache.rb
rbbt-util-5.34.15 lib/rbbt/util/filecache.rb
rbbt-util-5.34.14 lib/rbbt/util/filecache.rb
rbbt-util-5.34.13 lib/rbbt/util/filecache.rb
rbbt-util-5.34.12 lib/rbbt/util/filecache.rb
rbbt-util-5.34.11 lib/rbbt/util/filecache.rb
rbbt-util-5.34.10 lib/rbbt/util/filecache.rb
rbbt-util-5.34.9 lib/rbbt/util/filecache.rb
rbbt-util-5.34.8 lib/rbbt/util/filecache.rb
rbbt-util-5.34.7 lib/rbbt/util/filecache.rb
rbbt-util-5.34.5 lib/rbbt/util/filecache.rb
rbbt-util-5.34.4 lib/rbbt/util/filecache.rb
rbbt-util-5.34.3 lib/rbbt/util/filecache.rb
rbbt-util-5.34.2 lib/rbbt/util/filecache.rb
rbbt-util-5.34.1 lib/rbbt/util/filecache.rb
rbbt-util-5.34.0 lib/rbbt/util/filecache.rb
rbbt-util-5.33.21 lib/rbbt/util/filecache.rb
rbbt-util-5.33.20 lib/rbbt/util/filecache.rb
rbbt-util-5.33.19 lib/rbbt/util/filecache.rb