Sha256: 9d4f9dc446f7bc7c721b720cf51b7723160489f394315cf806bd48c5b0d27804
Contents?: true
Size: 1.33 KB
Versions: 1
Compression:
Stored size: 1.33 KB
Contents
# -- The settings table; has support for ttl etc. --------------------------- require "json" class MicroSql::KeyValueTable < MicroSql::Table def initialize(db, table_name = "settings") super db, "CREATE TABLE #{table_name}(uid TEXT PRIMARY KEY, value TEXT, ttl INTEGER NOT NULL)" end def [](key) value, ttl = db.ask("SELECT value, ttl FROM #{table_name} WHERE uid=?", key) decode(value) if ttl && (ttl == 0 || ttl > Time.now.to_i) end def delete_all @db.exec "DELETE FROM #{table_name}" end def cached(key, ttl = nil, &block) self[key] || update(key, yield, ttl) end def update(key, value, ttl = nil) if value encoded = encode(value) ttl = ttl ? ttl + Time.now.to_i : 0 affected = @db.ask("UPDATE #{table_name} SET value=?, ttl=? WHERE uid=?", encoded, ttl, key) if affected == 0 @db.ask("INSERT INTO #{table_name}(value, ttl, uid) VALUES(?,?,?)", encoded, ttl, key) end else @db.ask("DELETE FROM #{table_name} WHERE uid=?", key) end value end def expire(key, ttl) ttl = ttl ? ttl + Time.now.to_i : ttl @db.ask("UPDATE #{table_name} SET ttl=? WHERE uid=?", ttl, key) end alias :[]= :update private def decode(io) return unless io JSON.parse("[#{io}]").first end def encode(value) value && value.to_json end end
Version data entries
1 entries across 1 versions & 1 rubygems
Version | Path |
---|---|
micro_sql-0.3.2 | lib/micro_sql/key_value_table.rb |