Class: Tairu::Cache::Disk

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

Instance Method Summary collapse

Constructor Details

#initialize(options = {}) ⇒ Disk

Returns a new instance of Disk.



6
7
8
9
10
# File 'lib/tairu/cache/disk.rb', line 6

def initialize(options={})
  raise "No path specified." unless options['path']
  @path = options['path']
  @expire = options['expire'] || 300
end

Instance Method Details

#add(name, coord, tile) ⇒ Object



42
43
44
45
46
47
48
49
# File 'lib/tairu/cache/disk.rb', line 42

def add(name, coord, tile)
  expire = Time.now + @expire
  base_path = File.join(File.expand_path(@path), name, "#{coord.zoom}", "#{coord.column}")
  FileUtils.mkdir_p(base_path)
  path = File.join(base_path, "#{coord.row}.#{Tairu.config.layers[name]['format']}")
  lock_write(path, tile.data)
  purge_expired(name)
end

#get(name, coord) ⇒ Object



51
52
53
54
55
56
57
58
59
# File 'lib/tairu/cache/disk.rb', line 51

def get(name, coord)
  layer = Tairu.config.layers[name]
  path = File.join(File.expand_path(@path), name, "#{coord.zoom}", "#{coord.column}", "#{coord.row}.#{layer['format']}")
  data = lock_read(path)
  
  return nil if data.nil?

  Tairu::Tile.new(data, layer['format'])
end

#lock_read(path) ⇒ Object



23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
# File 'lib/tairu/cache/disk.rb', line 23

def lock_read(path)
  if File.exists?(path)
    if File.mtime(path) > (Time.now - @expire)
      data = File.open(path, 'rb') do |f|
        begin
          f.flock(File::LOCK_SH)
          f.read
        ensure
          f.flock(File::LOCK_UN)
        end
      end
    else
      FileUtils.rm(path)
    end
  end

  data
end

#lock_write(path, data) ⇒ Object



12
13
14
15
16
17
18
19
20
21
# File 'lib/tairu/cache/disk.rb', line 12

def lock_write(path, data)
  File.open(path, 'wb') do |f|
    begin
      f.flock(File::LOCK_EX)
      f.write(data)
    ensure
      f.flock(File::LOCK_UN)
    end
  end
end

#purge_expired(name) ⇒ Object



61
62
63
64
65
66
# File 'lib/tairu/cache/disk.rb', line 61

def purge_expired(name)
  Dir.glob(File.join(File.expand_path(@path), "**/*.#{Tairu.config.layers[name]['format']}")).each do |f|
    FileUtils.rm(f) if File.mtime(f) < (Time.now - @expire)
  end
  Dir[File.join(File.expand_path(@path), '**/*')].select {|d| File.directory?(d)}.select {|d| (Dir.entries(d) - %w[. ..]).empty?}.each {|d| Dir.rmdir(d)}
end