Class: Cache

Inherits:
Object
  • Object
show all
Defined in:
lib/itinerary/cache.rb

Instance Method Summary collapse

Constructor Details

#initialize(dir) ⇒ Cache

Returns a new instance of Cache.



3
4
5
6
# File 'lib/itinerary/cache.rb', line 3

def initialize(dir)
  @dir = dir
  @dir.mkpath unless @dir.exist?
end

Instance Method Details

#fetch(key) ⇒ Object



26
27
28
# File 'lib/itinerary/cache.rb', line 26

def fetch(key)
  read(key) || yield.tap { |data| write(key, data) }
end

#path_for_key(key) ⇒ Object



8
9
10
# File 'lib/itinerary/cache.rb', line 8

def path_for_key(key)
  @dir + URI.encode(key).gsub(%r{/}, '_')
end

#read(key) ⇒ Object



12
13
14
15
16
17
18
19
# File 'lib/itinerary/cache.rb', line 12

def read(key)
  path = path_for_key(key)
  if path.exist?
    Marshal.load(path.read)
  else
    warn "[MISS #{key}]"
  end
end

#write(key, data) ⇒ Object



21
22
23
24
# File 'lib/itinerary/cache.rb', line 21

def write(key, data)
  path = path_for_key(key)
  path.open('w') { |io| io.write(Marshal.dump(data)) }
end