class FileSystem

Public Class Methods

new(config={}) click to toggle source

Construct a new File cache object.

param string dir

# File lib/handset_detection/cache/filesystem.rb, line 32
def initialize(config={})
  if config.include?('cache') and config['cache'].include?('file') and not config['cache']['file']['directory'].blank?
    dir = config['cache']['file']['directory']
  else
    dir = Dir.tmpdir
  end
  dir += File::SEPARATOR unless dir.match(/#{File::SEPARATOR}$/)
  raise 'Directory does not exist.' unless File.directory? dir
  raise 'Directory is not writable.' unless File.writable? dir
  @dir = dir
  @prefix = (config.include?('cache') and config['cache'].include?('prefix')) ? config['cache']['prefix'] : 'hd40'
end

Public Instance Methods

del(key) click to toggle source

Delete key

# File lib/handset_detection/cache/filesystem.rb, line 68
def del(key)
  fname = get_file_path key 
  return true unless File.file? fname
  File.unlink fname
end
flush() click to toggle source

Flush cache

# File lib/handset_detection/cache/filesystem.rb, line 75
def flush
  files = Dir.glob @dir + @prefix + '*'
  files.each do |file|
    File.unlink file if File.file? file
  end
  true
end
get(key) click to toggle source

Get key

# File lib/handset_detection/cache/filesystem.rb, line 47
def get(key)
  fname = get_file_path key 
  return nil unless File.file? fname

  data = File.readlines fname 
  exp = data.shift.to_i
  return nil if Time.now.to_i > exp and exp != -1

  Marshal::load data.join('')
end
get_file_path(key) click to toggle source

Get fully qualified path to file

# File lib/handset_detection/cache/filesystem.rb, line 84
def get_file_path(key)
  @dir + key 
end
set(key, data, ttl) click to toggle source

Set key

# File lib/handset_detection/cache/filesystem.rb, line 60
def set(key, data, ttl)
  fname = get_file_path key 
  File.open(fname, 'w') { |f| f.write((Time.now.to_i + ttl).to_s + "\n" + Marshal::dump(data)) }
  true
end