Sha256: 4aade967761a0464b5118ec2a195ef1e7b8646f5a3af67fa839540c558f225b1

Contents?: true

Size: 1.74 KB

Versions: 263

Compression:

Stored size: 1.74 KB

Contents

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

# Provides caching functionality for files downloaded from the internet
module FileCache
  CACHEDIR = "/tmp/rbbt_cache" 
  FileUtils.mkdir CACHEDIR 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.exists? FileCache.path(filename)
  end

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

    return nil if ! File.exists? 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

263 entries across 263 versions & 1 rubygems

Version Path
rbbt-util-5.20.9 lib/rbbt/util/filecache.rb
rbbt-util-5.20.8 lib/rbbt/util/filecache.rb
rbbt-util-5.20.7 lib/rbbt/util/filecache.rb
rbbt-util-5.20.6 lib/rbbt/util/filecache.rb
rbbt-util-5.20.5 lib/rbbt/util/filecache.rb
rbbt-util-5.20.4 lib/rbbt/util/filecache.rb
rbbt-util-5.20.3 lib/rbbt/util/filecache.rb
rbbt-util-5.20.2 lib/rbbt/util/filecache.rb
rbbt-util-5.20.1 lib/rbbt/util/filecache.rb
rbbt-util-5.20.0 lib/rbbt/util/filecache.rb
rbbt-util-5.19.37 lib/rbbt/util/filecache.rb
rbbt-util-5.19.36 lib/rbbt/util/filecache.rb
rbbt-util-5.19.35 lib/rbbt/util/filecache.rb
rbbt-util-5.19.34 lib/rbbt/util/filecache.rb
rbbt-util-5.19.32 lib/rbbt/util/filecache.rb
rbbt-util-5.19.31 lib/rbbt/util/filecache.rb
rbbt-util-5.19.30 lib/rbbt/util/filecache.rb
rbbt-util-5.19.29 lib/rbbt/util/filecache.rb
rbbt-util-5.19.28 lib/rbbt/util/filecache.rb
rbbt-util-5.19.27 lib/rbbt/util/filecache.rb