Module: Persistent

Included in:
Foo
Defined in:
lib/fsdb/persistent.rb

Overview

Mixin for an object that persists in a file by itself.

References from the object to objects which need to persist separately should be through nonpersistent_attr_accessors. Otherwise, objects referred to in attrs will persist in the same file.

Class Method Summary collapse

Instance Method Summary collapse

Class Method Details

.load(*args) ⇒ Object



61
62
63
# File 'lib/fsdb/persistent.rb', line 61

def load(*args)
  Marshal.load(*args)
end

.restore(file) ⇒ Object

Need to take care that only one thread in the process is restoring a particular object, or there will be multiple copies.



51
52
53
54
55
56
57
58
59
# File 'lib/fsdb/persistent.rb', line 51

def restore file
  object = File.open(file, "rb") do |f|
    f.lock_shared_fsdb do
      load(f)
    end
  end
  object.restore file
  object
end

Instance Method Details

#dump(*args) ⇒ Object



38
39
40
# File 'lib/fsdb/persistent.rb', line 38

def dump(*args)
  Marshal.dump(self, *args)
end

#persistent_fileObject



42
43
44
45
# File 'lib/fsdb/persistent.rb', line 42

def persistent_file
  raise "#{self.class} must define the #persistent_file method to" +
        " return the path of the file in which object persists."
end

#persistent_mutexObject



15
16
17
18
19
20
# File 'lib/fsdb/persistent.rb', line 15

def persistent_mutex
  @persistent_mutex ||
    Thread.exclusive do
      @persistent_mutex ||= Mutex.new  # ||= to prevent race condition
    end
end

#restore(file) ⇒ Object

Called when the object is loaded, allowing the object to restore some state from the path at which it was saved.



69
# File 'lib/fsdb/persistent.rb', line 69

def restore file; end

#saveObject

Save the persistent object (and all of its persistent references) to its file. If a block is given, call it (with self) in the context of locks that protect the file from other threads and processes. This can be used to atomically save related objects in separate files.



26
27
28
29
30
31
32
33
34
35
36
# File 'lib/fsdb/persistent.rb', line 26

def save
  persistent_mutex.synchronize do
    File.makedirs(File.dirname(persistent_file))
    File.open(persistent_file, "wb") do |f|
      f.lock_exclusive_fsdb do
        dump(f)
        yield self if block_given?
      end
    end
  end
end