lib/volatiledb.rb in volatiledb-0.0.2 vs lib/volatiledb.rb in volatiledb-0.0.3
- old
+ new
@@ -7,23 +7,97 @@
def initialize
@raw ||= Volatile::Raw.new
@db ||= {}
end
- def put(key, &action)
- @db[key] = action
- @raw.put(key, action.call)
+ #
+ # 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.
+ #
def get(key)
data = @raw.get key
- unless data.nil?
+ if data.nil?
+ sync key
+ else
data
+ end
+ end
+
+ #
+ # Works the same as get, but will fire the action defined for the given key
+ # after the timeout defined for that key has elapsed.
+ #
+ 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.
+ #
+ def pull(key)
+ sync key
+ end
+
+ private
+ def populate_db(key, timeout, action)
+ @db[key] = {
+ :action => action,
+ :timeout => timeout,
+ :last_access => now
+ }
+ end
+
+ def sync(key)
+ touch key
+ save key
+ end
+
+ def touch(key)
+ checking(key) {|k| @db[k][:last_access] = now }
+ end
+
+ def now
+ Time.now.to_i
+ end
+
+ def save(key)
+ raw_put key
+ raw_get key
+ end
+
+ def raw_put(key)
+ checking(key) {|k| @raw.put(k, @db[k][:action].call) }
+ end
+
+ def raw_get(key)
+ checking(key) {|k| @raw.get k }
+ end
+
+ def checking(key)
+ if @db.key?(key)
+ yield(key)
else
- @raw.put(key, @db[key].call)
- @raw.get(key)
+ nil
end
end
end
class Raw
@@ -39,10 +113,10 @@
end
def get(key)
handle = @db[key]
f = "/tmp/#{handle}"
- if File.exists?(f)
+ if File.file?(f)
File.read f
else
nil
end
end