Class: Cue::Store::File

Inherits:
Object
  • Object
show all
Includes:
Enumerable
Defined in:
lib/cue/store/file.rb

Instance Method Summary collapse

Constructor Details

#initialize(root_path = nil) ⇒ File



10
11
12
13
# File 'lib/cue/store/file.rb', line 10

def initialize(root_path=nil)
  @root_path = root_path
  FileUtils.mkdir_p(items_path)
end

Instance Method Details

#clearObject



15
16
17
# File 'lib/cue/store/file.rb', line 15

def clear
  keys.each { |key| delete(key) }
end

#delete(key) ⇒ Object



19
20
21
22
23
# File 'lib/cue/store/file.rb', line 19

def delete(key)
  FileUtils.rm_r(item_path(key))
  key_dir = dir_for(key)
  FileUtils.rm_r(key_dir) if Dir[::File.join(key_dir, '*')].empty?
end

#each {|items| ... } ⇒ Object

Yields:

  • (items)


25
26
27
28
# File 'lib/cue/store/file.rb', line 25

def each
  items = keys.map(&method(:read)).sort
  yield(items)
end

#keysObject



30
31
32
33
34
35
36
37
38
39
40
41
42
# File 'lib/cue/store/file.rb', line 30

def keys
  keys = []
  
  Dir.glob(::File.join(items_path, '*')).each do |prefix_dir|
    prefix = ::File.basename(prefix_dir)
    Dir.glob(::File.join(prefix_dir, '*')).each do |suffix_file|
      suffix = ::File.basename(suffix_file)
      keys << (prefix + suffix)
    end
  end
  
  keys
end

#read(key) ⇒ Object



44
45
46
47
48
49
50
51
52
53
54
# File 'lib/cue/store/file.rb', line 44

def read(key)
  return nil unless ::File.exists?(item_path(key))
  
  data = nil
  file_for_reading(item_path(key)) do |file|
    data = uncompress(file.read)
  end
  return data if data.nil?
  
  deserialize(data)
end

#write(key, item) ⇒ Object



56
57
58
59
60
61
62
# File 'lib/cue/store/file.rb', line 56

def write(key, item)
  FileUtils.mkdir_p(dir_for(key))
  file_for_writing(item_path(key)) do |file|
    data = compress(serialize(item))
    file.write(data)
  end
end