Class: DiskStore

Inherits:
Object
  • Object
show all
Defined in:
lib/disk_store.rb,
lib/disk_store/reaper.rb,
lib/disk_store/version.rb,
lib/disk_store/eviction_strategies/lru.rb

Defined Under Namespace

Classes: Reaper

Constant Summary collapse

DIR_FORMATTER =
"%03X"
FILENAME_MAX_SIZE =

max filename size on file system is 255, minus room for timestamp and random characters appended by Tempfile (used by atomic write)

228
EXCLUDED_DIRS =
['.', '..'].freeze
VERSION =
"0.3.0"

Instance Attribute Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(path = nil, opts = {}) ⇒ DiskStore

Returns a new instance of DiskStore.



11
12
13
14
15
16
# File 'lib/disk_store.rb', line 11

def initialize(path=nil, opts = {})
  path ||= "."
  @root_path = File.expand_path path
  @options = opts
  @reaper = Reaper.spawn_for(@root_path, @options)
end

Instance Attribute Details

#reaperObject (readonly)

Returns the value of attribute reaper.



9
10
11
# File 'lib/disk_store.rb', line 9

def reaper
  @reaper
end

Instance Method Details

#delete(key) ⇒ Object



43
44
45
46
47
48
49
50
# File 'lib/disk_store.rb', line 43

def delete(key)
  file_path = key_file_path(key)
  if exist?(key)
    File.delete(file_path)
    delete_empty_directories(File.dirname(file_path))
  end
  true
end

#exist?(key) ⇒ Boolean

Returns:

  • (Boolean)


39
40
41
# File 'lib/disk_store.rb', line 39

def exist?(key)
  File.exist?(key_file_path(key))
end

#fetch(key) ⇒ Object



52
53
54
55
56
57
58
59
60
61
62
63
64
# File 'lib/disk_store.rb', line 52

def fetch(key)
  if block_given?
    if exist?(key)
      read(key)
    else
      io = yield
      write(key, io)
      read(key)
    end
  else
    read(key)
  end
end

#read(key) ⇒ Object



18
19
20
# File 'lib/disk_store.rb', line 18

def read(key)
  File.open(key_file_path(key), 'rb')
end

#write(key, io) ⇒ Object



22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
# File 'lib/disk_store.rb', line 22

def write(key, io)
  file_path = key_file_path(key)
  ensure_cache_path(File.dirname(file_path))

  File.open(file_path, 'wb') do |f|
    begin
      f.flock File::LOCK_EX
      IO::copy_stream(io, f)
    ensure
      # We need to make sure that any data written makes it to the disk.
      # http://stackoverflow.com/questions/6701103/understanding-ruby-and-os-i-o-buffering
      f.fsync
      f.flock File::LOCK_UN
    end
  end
end