Class: Tap::Support::Persistence

Inherits:
Object
  • Object
show all
Defined in:
lib/tap/support/persistence.rb

Overview

A very simple wrapper for root providing a CRUD interface for reading and writing files.

Instance Attribute Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(root) ⇒ Persistence

Initializes a new persistence wrapper for the specified root.



12
13
14
# File 'lib/tap/support/persistence.rb', line 12

def initialize(root)
  @root = root
end

Instance Attribute Details

#rootObject (readonly)

The Tap::Root for self.



9
10
11
# File 'lib/tap/support/persistence.rb', line 9

def root
  @root
end

Instance Method Details

#create(id) ⇒ Object

Creates the file for the specified id. If a block is given, an io to the file will be yielded to it; otherwise the file will be created without content. Returns the path to the persistence file.

Raises an error if the file already exists.



36
37
38
39
40
# File 'lib/tap/support/persistence.rb', line 36

def create(id)
  filepath = path(id)
  raise "already exists: #{filepath}" if File.exists?(filepath)
  root.prepare(filepath) {|io| yield(io) if block_given? }
end

#destroy(id) ⇒ Object

Removes the persistence file for id, if it exists. Returns true if the file was removed.



58
59
60
61
62
63
64
65
66
67
# File 'lib/tap/support/persistence.rb', line 58

def destroy(id)
  filepath = path(id)
  
  if File.file?(filepath)
    FileUtils.rm(filepath)
    true
  else
    false
  end
end

#indexObject

Returns a list of existing ids.



23
24
25
26
27
28
29
# File 'lib/tap/support/persistence.rb', line 23

def index
  root.glob(:data).select do |path|
    File.file?(path)
  end.collect do |path|
    root.relative_filepath(:data, path)
  end
end

#path(id) ⇒ Object

Returns the filepath for the specified id. Non-string ids are allowed; they will be converted to strings using to_s.



18
19
20
# File 'lib/tap/support/persistence.rb', line 18

def path(id)
  root.subpath(:data, id.to_s)
end

#read(id) ⇒ Object

Reads and returns the data for the specified id, or an empty string if the persistence file doesn’t exist.



44
45
46
47
# File 'lib/tap/support/persistence.rb', line 44

def read(id)
  filepath = path(id)
  File.file?(filepath) ? File.read(filepath) : ''
end

#update(id) ⇒ Object

Overwrites the data for the specified id. A block must be given to provide the new content; a persistence file will be created if one does not exist already.



52
53
54
# File 'lib/tap/support/persistence.rb', line 52

def update(id)
  root.prepare(path(id)) {|io| yield(io) }
end