Class: Hubtime::Cacher

Inherits:
Object
  • Object
show all
Defined in:
lib/hubtime/cacher.rb

Class Method Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(directory) ⇒ Cacher

Returns a new instance of Cacher.



19
20
21
22
23
# File 'lib/hubtime/cacher.rb', line 19

def initialize(directory)
  root = File.join(File.expand_path("."), "data", "cache")
  @directory = File.join(root, directory)
  FileUtils.mkdir_p(@directory)
end

Class Method Details

.clear(type) ⇒ Object



5
6
7
8
9
10
11
12
13
14
15
16
17
18
# File 'lib/hubtime/cacher.rb', line 5

def self.clear(type)
  dir = nil
  case type
  when "all"
    dir = File.join(File.expand_path("."), "data")
  when "cache", "charts"
    dir = File.join(File.expand_path("."), "data", type)
  else
    dir = File.join(File.expand_path("."), "data", "cache", type)
  end

  raise "Unknown clear type" unless dir
  FileUtils.rm_rf(dir, :secure => true) if File.exist?(dir)
end

Instance Method Details

#read(key) ⇒ Object



25
26
27
28
29
# File 'lib/hubtime/cacher.rb', line 25

def read(key)
  file_name = File.join(@directory, sanitized_file_name_from(key))
  return nil unless File.exist?(file_name)
  YAML.load(File.read(file_name))
end

#write(key, value) ⇒ Object



31
32
33
34
35
36
37
# File 'lib/hubtime/cacher.rb', line 31

def write(key, value)
  file_name = File.join(@directory, sanitized_file_name_from(key))
  directory = File.dirname(file_name)
  FileUtils.mkdir_p(directory) unless File.exist?(directory)
  File.open(file_name, 'w') {|f| f.write(YAML.dump(value)) }
  value
end