Class: DiskStore

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

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.1.2"

Instance Method Summary collapse

Constructor Details

#initialize(path = nil) ⇒ DiskStore

Returns a new instance of DiskStore.



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

def initialize(path=nil)
  path ||= "."
  @root_path = File.expand_path path
end

Instance Method Details

#delete(key) ⇒ Object



38
39
40
41
42
43
44
45
# File 'lib/disk_store.rb', line 38

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)


34
35
36
# File 'lib/disk_store.rb', line 34

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

#fetch(key) ⇒ Object



47
48
49
50
51
52
53
54
55
56
57
58
59
# File 'lib/disk_store.rb', line 47

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



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

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

#write(key, io) ⇒ Object



17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
# File 'lib/disk_store.rb', line 17

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