lib/volatiledb.rb in volatiledb-0.0.3 vs lib/volatiledb.rb in volatiledb-0.0.4
- old
+ new
@@ -1,36 +1,46 @@
require "volatiledb/version"
require 'digest/sha1'
+#
+# Main module. See DB class.
+#
module Volatile
+ #
+ # The main DB class. This is the public API for the library.
+ #
class DB
+
+ #
+ # Constructor, nothing fancy.
+ #
def initialize
@raw ||= Volatile::Raw.new
@db ||= {}
end
#
# Define an action for a given key. The action should return a String.
# A timeout in seconds may optionally be defined. Default is 3 seconds.
#
- # This method should be called before using any of the read operations.
- #
def put(key, timeout=3, &action)
populate_db key, timeout, action
raw_put key
key
end
#
- # Read the data for the given key from storage. If the underlying storage
- # has disappeared, it will be re-initialized by calling the action defined
- # for that key again. After the storage has been re-initialized, its value
- # will be read and returned.
+ # Read the data for the given key from storage. If the underlying
+ # storage has disappeared, it will be re-initialized by calling
+ # the action defined for that key again. After the storage has
+ # been re-initialized, its value will be read and returned.
#
+ # Returns nil for a key which has not had any action defined for it yet.
+ #
def get(key)
- data = @raw.get key
+ data = raw_get key
if data.nil?
sync key
else
data
end
@@ -38,22 +48,27 @@
#
# Works the same as get, but will fire the action defined for the given key
# after the timeout defined for that key has elapsed.
#
+ # Returns nil for a key which has not had any action defined for it yet.
+ #
def fetch(key)
checking key do |k|
item = @db[k]
delta = now - item[:last_access]
delta > item[:timeout] ? sync(k) : get(k)
end
end
#
# Works the same as fetch, but ignores timeout and calls the defined action
- # every time.
+ # every time. Should be used sparingly as it re-initializes storage on every
+ # call.
#
+ # Returns nil for a key which has not had any action defined for it yet.
+ #
def pull(key)
sync key
end
private
@@ -98,21 +113,34 @@
nil
end
end
end
+ #
+ # Implementation detail. Not intended for direct instantiation.
+ #
class Raw
+
+ #
+ # Implementation detail.
+ #
def initialize
@db ||= {}
end
+ #
+ # Implementation detail.
+ #
def put(key, data)
handle = handle_from key
File.open("/tmp/#{handle}", "w") {|f| f << data}
@db[key] = handle
key
end
+ #
+ # Implementation detail.
+ #
def get(key)
handle = @db[key]
f = "/tmp/#{handle}"
if File.file?(f)
File.read f